使用Python将海量数据批量插入SQLite

2024-03-10

我读到了这个:使用 Python 将 CSV 文件导入 sqlite3 数据库表 https://stackoverflow.com/questions/2887878/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()

由于这是谷歌搜索的最高结果,我认为更新这个问题可能会很好。

来自python sqlite 文档 https://docs.python.org/2/library/sqlite3.html#sqlite3-controlling-transactions您可以使用

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 行插入,速度快如闪电。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用Python将海量数据批量插入SQLite 的相关文章

随机推荐