【问题标题】:Inserting millions of rows into a SQLite3 table using Flask-SQLAlchamy and Python3使用 Flask-SQLAlchamy 和 Python3 将数百万行插入到 SQLite3 表中
【发布时间】:2018-06-25 12:14:28
【问题描述】:

如何使用 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)

.txtfile 中的行如下所示:

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

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

【问题讨论】:

标签: python python-3.x flask sqlite flask-sqlalchemy


【解决方案1】:

我找到了一种可以显着加快交易速度的解决方案。我使用的答案来自:https://stackoverflow.com/a/7137270/9988919https://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)

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2017-10-20
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多