python - 使用 psycopg2 在 python 上进行多进程

标签 python postgresql multiprocessing psycopg2

我正在使用 python 将许多记录添加到 Postgres 数据库中,因为我必须插入数百万条记录,我需要并行化 2 个函数:

insert_A(cur)  
insert_B(cur) 

哪里:

conn=psycopg2.connect(.....)
cur = conn.cursor() 

我尝试了一个解决方案,我在此处的另一篇文章中找到了堆栈溢出,例如:

result1= pool.apply_async(insert_A, cur)  
result2= pool.apply_async(insert_B, cur)  
answer1=result1.get(timeout=15)  
answer2=result2.get(timeout=15)  

但是我得到了这个错误: 回溯(最近调用最后):

中的文件“test.py”,第 387 行 answer1=result1.get(timeout=15)
文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py”,第 558 行,在 get
提高 self 值(value)
psycopg2.InterfaceError: 游标没有连接

有人可以帮助我吗? :(

最佳答案

最后我是这样解决的:

if __name__ == '__main__':
    p = Process(target=insert_A, args=(ARG,))
    q = Process(target=insert_measurement_real, args=(ARG,))
    p.start()
    q.start()
    p.join()
    q.join()

并在函数内部创建连接而不是在函数外部创建它(并将连接作为参数传递)...

关于python - 使用 psycopg2 在 python 上进行多进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366845/

相关文章:

linux - 用于 FS 在 x86 SMP 中启动的工作 linux 内核 + gem5 配置

python - 如何只删除或编辑sql表中的一行?

php - 将 Python 或 Perl 与 PHP 集成

sql - 如何在 PostgreSQL 的函数内返回 SELECT 的结果?

postgresql - 在查询 PostgreSQL 数据库的黑盒函数上使用 multiprocessing.Pool 时为 "InterfaceError: connection already closed"

python - 多处理池示例(并行)比顺序处理慢。尝试理解Python中的池

python - python的快速二维 float 组(访问/写入)

python - 如何使用 python(2.5 版)压缩文件夹的内容?

laravel - 一小时间隔 - Laravel

php - 将数组绑定(bind)到 =ANY() 条件的 SQL 注入(inject)