我读到这个:Importing a CSV file into a sqlite3 database table using Python
似乎每个人都建议使用逐行阅读而不是使用 SQLite 中的批量 .import。但是,如果您有数百万行数据,这将使插入变得非常缓慢。有没有其他方法可以规避这个问题?
更新:我尝试了以下代码逐行插入,但速度没有我预期的那么好。有没有改进的地方
for logFileName in allLogFilesName:
logFile = codecs.open(logFileName, 'rb', encoding='utf-8')
for logLine in logFile:
logLineAsList = logLine.split('\t')
output.execute('''INSERT INTO log VALUES(?, ?, ?, ?)''', logLineAsList)
logFile.close()
connection.commit()
connection.close()
最佳答案
由于这是 Google 搜索的最高结果,我认为更新此问题可能会很好。
来自 python sqlite docs你可以使用
import sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table person(firstname, lastname)")
# Fill the table
con.executemany("insert into person(firstname, lastname) values (?,?)", persons)
我已经使用这种方法一次提交超过 50k 行插入,而且速度非常快。
关于python - 使用 Python 将大量数据批量插入 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18219779/