【问题标题】:Bulk Insert Data from List of Dictionaries into Postgresql database [Faster Way]?将字典列表中的数据批量插入 Postgresql 数据库 [更快的方式]?
【发布时间】:2018-07-20 15:55:10
【问题描述】:

例如:

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 万条记录要插入到表中。 现在我正在做的是遍历字典列表并获取所需的键/值对并一一插入

def insert_books(self, val):
    cur = self.con.cursor()
    sql = """insert into testtable values {}""".format(val)
    cur.execute(sql)
    self.con.commit()
    cur.close()

for i in books:
    result = i['author'],i['price']
    db_g.insert_books(result)   #db_g is class - connection properties

那么有没有一种更快更简单的方法来一次批量插入 10k 等数据?

【问题讨论】:

  • 你的数据库是什么?这种性能优化往往是特定于数据库的。
  • 数据库:Postgresql。
  • 该 dup 目标的一些基本原理——您距离拥有一个元组列表只有 1 步之遥,同时执行所有这些操作的事务将更少。您应该能够使用该帖子中的信息推断出如何在一笔交易中执行此操作
  • 效果很好。谢谢@MoxieBall

标签: python list dictionary


【解决方案1】:

我认为通过转储整个数据帧进行批量插入会更快..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)

希望对你有帮助

【讨论】:

  • 你可以更清楚地解释这一点。批量插入更可取,因为它减少了查询的数量。我认为从字典创建数据框不会有帮助。看一下这个。 docs.sqlalchemy.org/en/latest/faq/performance.html
  • @mad_ 嘿,感谢您指出这一点!刚刚通过 pd.to_sql,我认为还有多个查询仍在执行,但我认为这种方法要简单得多.. :)
猜你喜欢
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多