首页 新闻 论坛 群组 Blog 文档 下载 读书 Tag 网摘 搜索 开源 FAQ 第二书店 博文视点 程序员
频道: 研发 数据库 中间件 信息化 视频 .NET Java 游戏 移动 服务: 人才 外包 培训
    图书品种:235680
       
热门搜索: ASP.NET Ajax Spring Hibernate Java

14.7  得到数据

DB-API说明书的很大一部分都是关于如何从数据库得到数据。查询通过cursor的execute()方法发出,结果通过cursor的众多以fetch开头的方法返回。在这部分将详细介绍这些方法的不同,并通过例子来说明每个方法。

14.7.1  使用fetchall()

fetchall()函数可以获得结果集中的所有行(或者是除了已经使用其他函数得到的行之外的所有)。它返回一个顺序的list(例如tuple或list)。list中的每个顺序都表示一个记录,而列表示了顺序中的条目。

在大多数情况下,使用fetchall()非常简单。然而必须谨慎小心,确保结果集的大小是可处理的。当使用fetchall()时,结果的所有内容都将被载入内存,所以如果您正取得一个大的数据,就不应该使用fetchall()。下面是一个使用fetchall()的例子:

#!/usr/bin/env python

# fetchall() - Chapter 14

# fetchall.py

# Adjust the connect() call below for your database.

import psycopg

dbh = psycopg.connect('dbname=jgoerzen user=jgoerzen')

print "Connection successful."

cur = dbh.cursor()

cur.execute("SELECT * FROM ch14")

rows = cur.fetchall()

for row in rows:

    print row

dbh.close()

在这个例子中,您简单地请求了ch14表中所有的数据,并打印出每一行。结果看上去如下:

$ ./fetchall.py

Connecting to dbname=jgoerzen user=jgoerzen

Connection successful.

(0, 'Zero')

(1, 'Item One')

(2, 'Item Two')

(3, 'Three')

14.7.2  使用fetchmany()

有时候可能使用fetchall()不合适,例如在需要处理的结果很大的情况下。但是如果您还想成块地接收数据,fetchmany()函数是很好的选择。它的返回和fetchall()一样,但是它本身限制每次调用返回的数量。所以,您必须在接收完全部数据之前继续调用它。当没有数据返回时,fetchmany()将返回空。

您可以通过预先设置cursor的arraysize属性来决定每次返回的结果数,或者您可以传递给fetchmany()一个指定的大小来覆盖原来的。下面是一个使用fetchmany()的例子:

#!/usr/bin/env python

# fetchmany() - Chapter 14 - fetchmany.py

# Adjust the connect() call below for your database.

import psycopg

dbh = psycopg.connect('dbname=jgoerzen user=jgoerzen')

print "Connection successful."

cur = dbh.cursor()

cur.execute("SELECT * FROM ch14")

cur.arraysize = 2

while 1:

    rows = cur.fetchmany()

    print "Obtained %d results from fetchmany()." % len(rows)

    if not len(rows):

        break

 

    for row in rows:

        print row

dbh.close()

这段代码和fetchall()类似,除了这里有个简单的loop循环。我设置的arraysize要比实际系统中的低很多,这样可以阐明fetchmany()的效果。下面是该例子的输出:

$ ./fetchmany.py

Connection successful.

Obtained 2 results from fetchmany().

(0, 'Zero')

(1, 'Item One')

Obtained 2 results from fetchmany().

(2, 'Item Two')

(3, 'Three')

Obtained 0 results from fetchmany().

14.7.3  使用fetchone()

最后一个取得数据的函数是fetchone()。这个函数将返回一个单独的行。如果没有数据了,它返回None。由于fetchone()每次只返回一条单独的行,这样就不用担心内存了。

另一方面,使用某些数据库的时候,在处理较大数据的时候,这个函数要比fetchmany()和fetchall()速度慢。然而,在多数情况下,这个性能的差异是可以忽略的。下面是一个fetchone()的例子:

#!/usr/bin/env python

# fetchone() - Chapter 14 - fetchone.py

# Adjust the connect() call below for your database.

import psycopg

dbh = psycopg.connect('dbname=jgoerzen user=jgoerzen')

print "Connection successful."

cur = dbh.cursor()

cur.execute("SELECT * FROM ch14")

cur.arraysize = 2

while 1:

    row = cur.fetchone()

    if row is None:

        break

    print row

dbh.close()

运行这个程序,您会得到下面的结果:

$ ./fetchone.py

Connection successful.

(0, 'Zero')

(1, 'Item One')

(2, 'Item Two')

(3, 'Three')

查看所有评论(0)条】

最近评论



正在载入评论列表...
热点评论