python在sqlite3中批量快速插入数据
初始化sqlite示例import sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con= sqlite3.connect(":memory:")
# Create the table
con.execute("create table person(firstname, lastname)")
如果您需要一次在数据库中插入很多行,则实际上不应该使用execute。该sqlite3模块提供了批量插入的方法:executemany。
而不是做类似的事情:for row in iter_data():
con.execute('INSERT INTO person VALUES (?)', row)
利用executemany,参数接受生成器tuples:# Fill the table
con.executemany(
"insert into person(firstname, lastname) values (?,?)", persons
)
这不仅更简洁,而且效率更高。实际上,sqlite3工具是在execute实际使用executemany,但是execute插入的是一行而不是多行数据。
注意:
values中的问号数量==插入的字段数量。否则执行查询语句时,运行错误。
参考:
https://remusao.github.io/posts/few-tips-sqlite-perf.html