gpt4 book ai didi

Python Psycopg2 For 循环,大型数据库问题

转载 作者:行者123 更新时间:2023-11-29 13:02:55 26 4
gpt4 key购买 nike

我正在尝试使用 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、bytes、datetime:psycopg2.ProgrammingError:没有要获取的结果

最佳答案

看起来您正在将一个元组传递给 cursor.execute。尝试传递要运行的 sql 字符串。

statement = "select source_ip,dest_ip,bytes,datetime from IPS"
cursor.execute(statement)

关于Python Psycopg2 For 循环,大型数据库问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23894393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com