将字典列表中的数据大容量插入Postgresql数据库[更快的方式]?

2024-05-16 04:27:43 发布

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

例如:

books = [{'name':'pearson', 'price':60, 'author':'Jesse Pinkman'},{'name':'ah publications', 'price':80, 'author':'Gus Fring'},{'name':'euclidean', 'price':120, 'author':'Skyler White'},{'name':'Nanjial', 'price':260, 'author':'Saul Goodman'}]

我需要通过取'author'、'price'将每个字典插入已经创建的表中 我有大约10万条记录要插入表中。 现在我要做的是循环查看字典列表,获取所需的键/值对,然后逐个插入

^{pr2}$

那么,有没有一种更快速、更简单的方法一次大容量插入数据,比如10k?在


Tags: name字典bookspriceauthorwhitepearsonpublications
1条回答
网友
1楼 · 发布于 2024-05-16 04:27:43

我认为通过转储整个数据帧进行大容量插入会更快。Why Bulk Import is faster than bunch of INSERTs?

import sqlalchemy

def db_conn():
    connection = sqlalchemy.create_engine(//connection string)
    return connection 


books = [{'name':'pearson', 'price':60, 'author':'Jesse Pinkman'},{'name':'ah publications', 'price':80, 'author':'Gus Fring'},{'name':'euclidean', 'price':120, 'author':'Skyler White'},{'name':'Nanjial', 'price':260, 'author':'Saul Goodman'}]

df_to_ingest = pd.DataFrame(books)
df_to_ingest = df_to_ingest([['author', 'price']])

df_to_ingest('tablename', db_conn(), if_exists='append', index=False)

希望这有帮助

相关问题 更多 >