【发布时间】:2014-05-27 16:23:40
【问题描述】:
我正在尝试使用 psycopg2 和 python 遍历一个 8gb 的大型数据库。我已按照文档进行操作,但出现错误。我试图在不使用 .fetchall() 的情况下遍历数据库的每一行,因为它太大了,无法将其全部提取到内存中。您不能使用 fetchone(),因为它会单独获取每一列。
注意第一次通过会返回值,第二次通过会报错。
文档内容如下:
Note cursor objects are iterable, so, instead of calling explicitly fetchone() in a loop, the object itself can be used:
>>> cur.execute("SELECT * FROM test;")
>>> for record in cur:
... print record
...
(1, 100, "abc'def")
(2, None, 'dada')
(3, 42, 'bar')
我的代码如下:
statement = ("select source_ip,dest_ip,bytes,datetime from IPS")
cursor.execute(statement)
for sip,dip,bytes,datetime in cursor:
if sip in cidr:
ip = sip
in_bytes = bytes
out_bytes = 0
time = datetime
else:
ip = dip
out_bytes = bytes
in_bytes = 0
time = datetime
cursor.execute("INSERT INTO presum (ip, in_bytes, out_bytes, datetime) VALUES (%s,%s,%s,%s);", (ip, in_bytes, out_bytes, time,))
conn.commit()
print "writing to presum"
我收到以下错误:
对于光标中的 sip、dip、字节、日期时间: psycopg2.ProgrammingError: 没有要获取的结果
【问题讨论】:
-
你是如何创建光标的?此外,您可以同时将同一个光标用于两个不同的目的,为此使用第二个光标。
-
@jjanes cursor = conn.cursor() 它不会让我只用光标来做我必须使用 fetchall() 它会用光标提取前几个值,但它会说没有结果获取但显然有总和
标签: python postgresql psycopg2