首页 > 解决方案 > 使用 Flask-SQLAlchamy 和 Python3 将数百万行插入到 SQLite3 表中

问题描述

如何使用 Flask-SQLAlchemy 将 .txt 文件中的数百万行或行插入 SQLite3 数据库?我尝试只从 .txt 文件中读取一行,然后循环添加和提交它们,但注意到这需要花费大量时间。我怎样才能有效地做到这一点?我尝试在我的代码中实施此解决方案https://stackoverflow.com/a/7137270,但无法使其正常工作。

表架构如下所示:

class table(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    col1 = db.Column(db.Integer)
    col2 = db.Column(db.Integer)
    col3 = db.Column(db.String(50))
    col4 = db.Column(db.String(50))
    col5 = db.Column(db.String(50))
    col6 = db.Column(db.Integer)
    col7 = db.Column(db.String(50))
    col8 = db.Column(db.Integer)
    col9 = db.Column(db.Integer)
    col10 = db.Column(db.Integer)
    col11 = db.Column(db.Integer)
    col12 = db.Column(db.Integer)

文件中的行.txt如下所示:

hjk;28770930;Y;T;C;;asd;;1;1233;1233;0.00081103

并且有大约 85M 行要添加到数据库中。

标签: pythonpython-3.xflasksqliteflask-sqlalchemy

解决方案


我找到了一种解决方案,可以显着加快交易速度。我使用的答案来自:https ://stackoverflow.com/a/7137270/9988919 https://stackoverflow.com/a/32271651/9988919

我不是一次读取一行并每次迭代写入一行,而是使用该def chunks()函数将文件分成块并产生一个生成器。然后在asdasd函数中循环块并在每个包含 10000 行的块之后提交。

我仍然很想知道是否有人能找到更快的方法,因为这也需要大约 5 个小时。

这是我的代码:

def chunks(data, n=10000):
    buffer = [None] * n
    idx = 0
    for record in data:
        buffer[idx] = record
        idx += 1
        if idx == n:
            yield buffer
            buffer = [None] * n
            idx = 0
    if idx > 0:
        yield buffer[:idx]

def load_data_table(filename):
    rows = 0
    csvData = csv.reader(open('./folder/{}'.format(filename), "r"), delimiter=";")
    dataset = tables.query.filter_by(id=1).first()
    divData = chunks(csvData)  # divide into 10000 rows each

    for chunk in divData:
        for col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12 in chunk:
            add_new = table(col1=col1, col2=col2, col3=col3, col4=col4, col5=col5, col6=col6, col7=col7, col8=col8, col9=col9, col10=col10, col11=col11, col12=col12)
            db.session.add(add_new)
        db.session.commit()
        rows += 10000
        print(rows)

推荐阅读