我正在将一个字典列表插入到PostgreSQL数据库中。该列表将快速增长,dict值(列)的数量约为30.数据显示:
projects = [
{'name': 'project alpha', 'code': 12, 'active': True},
{'name': 'project beta', 'code': 25, 'active': True},
{'name': 'project charlie', 'code': 46, 'active': False}
]
使用以下代码将数据插入PostgreSQL数据库确实有效(如在此answer中),但我担心执行太多查询。
for project in projects:
columns = project.keys()
values = project.values()
query = """INSERT INTO projects (%s) VALUES %s;"""
# print(cursor.mogrify(query, (AsIs(','.join(project.keys())), tuple(project.values()))))
cursor.execute(query, (AsIs(','.join(columns)), tuple(values)))
conn.commit()
有更好的做法吗?非常感谢您的帮助!
使用execute_values()在单个查询中插入数百行。
import psycopg2
from psycopg2.extras import execute_values
# ...
projects = [
{'name': 'project alpha', 'code': 12, 'active': True},
{'name': 'project beta', 'code': 25, 'active': True},
{'name': 'project charlie', 'code': 46, 'active': False}
]
columns = projects[0].keys()
query = "INSERT INTO projects ({}) VALUES %s".format(','.join(columns))
# convert projects values to sequence of seqeences
values = [[value for value in project.values()] for project in projects]
execute_values(cursor, query, values)
conn.commit()