【发布时间】: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