使用SQLAlchemy将记录更快地插入表中

Kyl*_*ndt 5 python mysql sql sqlite sqlalchemy

我正在解析日志并使用SQLAlchemy和Python将其插入MySQL或SQLite.现在我打开了与DB的连接,当我遍历每一行时,我在解析后插入它(这只是一个大表,现在对SQL不是很有经验).然后我在循环完成时关闭连接.汇总代码是:

log_table = schema.Table('log_table', metadata,
                         schema.Column('id', types.Integer, primary_key=True),
                         schema.Column('time', types.DateTime),
                         schema.Column('ip', types.String(length=15))
....
engine = create_engine(...)
metadata.bind = engine
connection = engine.connect()
....
for line in file_to_parse:
    m = line_regex.match(line)
    if m:
        fields = m.groupdict()
        pythonified = pythoninfy_log(fields) #Turn them into ints, datatimes, etc
        if use_sql:
            ins = log_table.insert(values=pythonified)
            connection.execute(ins)
            parsed += 1
Run Code Online (Sandbox Code Playgroud)

我的两个问题是:

  • 有没有办法加快这个基本框架内的插入?也许有一个插入队列和一些插入线程,某种批量插入等?
  • 当我使用MySQL时,大约120万条记录的插入时间为15分钟.使用SQLite,插入时间是一个多小时.db引擎之间的时间差异是否正确,或者它是否意味着我做了一些非常错误的事情?

Don*_*ows 4

您应该尝试的最重要的事情是围绕多个插入放置一个事务,因为将数据库提交到磁盘确实需要很长时间。您需要决定批处理级别,但粗略的第一次尝试是围绕整个批次进行交易。