gpt4 book ai didi

python - 使用 cursor.copy_from() 的 psycopg2 COPY 因大量输入而卡住

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

考虑 Python 中的以下代码,使用 psycopg2 cursor 对象(为清楚起见,更改或省略了一些列名称):

filename='data.csv'
file_columns=('id', 'node_id', 'segment_id', 'elevated',
'approximation', 'the_geom', 'azimuth')
self._cur.copy_from(file=open(filename),
table=self.new_table_name, columns=file_columns)
  • 数据库位于快速 LAN 上的远程机器上。
  • 使用 bash 中的 \COPY 运行速度非常快,即使对于大型(~1,000,000 行)文件也是如此。

此代码在 5,000 行时速度超快,但当 data.csv 超过 10,000 行时,程序会完全卡住。

有什么想法\解决方案吗?

亚当

最佳答案

这只是一种解决方法,但您可以将某些内容通过管道传输到 psql 中。当我懒得搞定 psycopg2 时,我有时会使用这个食谱

import subprocess
def psql_copy_from(filename, tablename, columns = None):
"""Warning, this does not properly quote things"""
coltxt = ' (%s)' % ', '.join(columns) if columns else ''
with open(filename) as f:
subprocess.check_call([
'psql',
'-c', 'COPY %s%s FROM STDIN' % (tablename, coltxt),
'--set=ON_ERROR_STOP=true', # to be safe
# add your connection args here
], stdin=f)

就您的锁定而言,您使用的是多线程还是类似的东西?

您的 postgres 是否记录了诸如关闭连接或死锁之类的任何信息?锁定后您能看到磁盘事件吗?

关于python - 使用 cursor.copy_from() 的 psycopg2 COPY 因大量输入而卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3491864/

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