gpt4 book ai didi

python-3.x - Psycopg2 - 如何进行大型查询 - 超过 100 万行

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

所以我正在尝试从本地的 postgresql 数据库进行大量查询。

'processrecords' 函数返回一个恶意软件对象列表,我假设每次运行服务器端游标时我都需要向主列表添加一个新列表。

我有点困惑,我该如何正确地做到这一点。

我想我需要使用服务器端游标,否则程序会用 Psycopg2 耗尽内存。但我听说过有关服务器端游标的好消息。

with connection:

cursor = connection.cursor()
with cursor:
cursor.itersize = 20000
cursor.execute("SELECT malware_id, malwarehashmd5, malwarehashsha1, malwarehashsha256g FROM malwarehashesandstrings")
listoffetchedmalware = cursor.fetchall()


listofmalwareobjects = processrecords(listoffetchedmalware)

最佳答案

对于 the documentation :

Psycopg wraps the database server side cursor in named cursors. A named cursor is created using the cursor() method specifying the name parameter.

尝试:

with connection:

cursor = connection.cursor('my_cursor')
...

但是,fetchall() 仍将一次返回所有行。如果要处理桶中的数据,请使用 fetchmany()在一个循环中,例如

with connection.cursor(name="my_cursor") as cursor:

cursor.itersize = 20000
cursor.execute(the_query)

listoffetchedmalware = cursor.fetchmany(cursor.itersize)

while len(listoffetchedmalware) > 0:

listofmalwareobjects = processrecords(listoffetchedmalware)
listoffetchedmalware = cursor.fetchmany(cursor.itersize)

关于python-3.x - Psycopg2 - 如何进行大型查询 - 超过 100 万行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57539015/

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