使用psycopg2将整数列表批量插入PostgreSQL表时报错如何解决
问题原因
- 核心调用错误:
cur.execute()仅支持单条SQL的参数绑定,你传入的是包含多组参数的元组列表,方法无法识别多组参数,因此抛出参数转换异常。 - 附加语法错误:你贴出的代码中
cur.execute调用末尾缺少右括号),修复该语法错误后仍然会触发参数绑定异常。
修复方案
方案1:使用executemany批量执行(改造成本最低)
psycopg2提供的executemany()方法专门用于批量执行同一条SQL语句,支持直接传入多组参数列表,修改后的代码如下:
import psycopg2 conn = psycopg2.connect(host="myhost", database="mydb", user="postgres", password="password", port="5432") cur = conn.cursor() arr = [1,2,3,4,5] arr2 = [(i,) for i in arr] # 替换execute为executemany cur.executemany("INSERT INTO my_table (my_value) VALUES (%s)", arr2) # 提交事务,否则插入不会生效 conn.commit() cur.close() conn.close()
方案2:使用PostgreSQLunnest函数(性能更优,适合大数据量)
直接将整数列表作为数组参数传入,利用PostgreSQL内置的unnest函数将数组展开为行,不需要提前转换为元组列表,插入效率比executemany更高:
import psycopg2 conn = psycopg2.connect(host="myhost", database="mydb", user="postgres", password="password", port="5432") cur = conn.cursor() arr = [1,2,3,4,5] cur.execute("INSERT INTO my_table (my_value) SELECT unnest(%s::int[])", (arr,)) conn.commit() cur.close() conn.close()
内容的提问来源于stack exchange,提问作者RocketSocks22
相关产品推荐
相关产品推荐

