psycopg2使用游标复制。COPY_from()使用大输入冻结

2024-06-07 00:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)
  • 数据库位于快速局域网上的远程计算机上。
  • 使用bash中的\COPY非常快,即使对于大型(~1000000行)文件也是如此。

这段代码对于5000行是超高速的,但是当data.csv超过10000行时,程序将完全冻结。

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

亚当


Tags: columnscsv对象代码selfidnodedata
2条回答

这就是内存限制,使得“copy_from”崩溃为open(filename)一次性返回所有文件。这是一个心理问题,不是Postgresql的问题,所以Mike的解决方案是最好的。

如果要将“copy_from”与常规提交一起使用并同时管理重复密钥,则有一个解决方案: https://stackoverflow.com/a/11059350/1431079

这只是一个解决方法,但您可以将某些内容导入psql。当我懒得把心理医生赶出来时,我有时会用这个食谱

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是否记录了诸如关闭的连接或死锁之类的内容?你能看到它锁定后的磁盘活动吗?

相关问题 更多 >