postgresql psycopg 2-正在将字典列表插入到PosgreSQL数据库中,执行次数太多?

neekobn8  于 2023-01-08  发布在  PostgreSQL
关注(0)|答案(3)|浏览(177)

我正在向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()

还有更好的做法吗?提前感谢您的帮助!

6tr1vspr

6tr1vspr1#

使用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 list of lists
values = [[value for value in project.values()] for project in projects]

execute_values(cursor, query, values)
conn.commit()
wnrlj8wa

wnrlj8wa2#

另一个不需要为字典列表处理太多数据的高性能选项是execute_batch(psycopg2version2.7中的新功能)。
例如:

import psycopg2
from psycopg2.extras import execute_batch

values = [{'name': 'project alpha', 'code': 12, 'active': True}, ...]
query = "INSERT INTO projects VALUES (%(name)s, %(code)s, %(active)s)"

execute_batch(cursor, query, values)
conn.commit()

https://www.psycopg.org/docs/extras.html#psycopg2.extras.execute_batch

相关问题