【问题标题】:SQL Database INSERT with Python - Performance使用 Python 插入 SQL 数据库 - 性能
【发布时间】:2020-04-03 08:19:42
【问题描述】:

我正在遍历不同的文本文件,将文本加载到字典中,然后连接到数据库并将这些文本插入到表中。

字典的字典,因为在每个文件中我都有多个文本块,其中包含我需要的不同部分的文本,例如名称、类型、内容等。因为我需要元排序信息,所以我将数据保存在这两层:文件级别和文本块级别

这是我的代码 - 首先是准备 DB INSERT 的字符串:

table_q = 'zz_querys'
query_id = 'query_name'
type_col = 'query_type'
descr_col = 'query_descr'
code_col = 'pure_code'

insertQuery = 'INSERT INTO [' + table_q + '] ([' + query_id + '], ' \
                                        '[' + type_col + '], ' \
                                        '[' + descr_col + '], ' \
                                        '[' + code_col + '])' \
                        '\nVALUES (?, ?, ?, ?)'

然后连接到数据库:

with conn:
    cursor = conn.cursor()
    for file, text_block in all_data.items():
        file = os.path.splitext(file)[0]
        for subtext in text_block:
            cat = text_block[subtext]
            qName = cat['query_name']
            qType = cat['type']
            qDescr = cat['descr_de']
            qCont = cat['content']
            cursor.execute(insertQuery, (qName, qType, qDescr, qCont))

所以在性能方面我觉得这效率不高 - 我每次运行循环(每个插入行)时都会调用 SQL INSERT 代码,但我最初不是来自技术方面,所以我不确定是否有一种方法更有效。

我的替代想法是将嵌套的字典结果加载到 pandas 数据框中(或从头开始将结果保存到数据框中),然后一次将整个数据框插入数据库。我以前没有在熊猫中这样做,但我认为应该是可能的。

这会对性能产生巨大影响吗?或者还有什么最有效的方法来做到这一点?

【问题讨论】:

  • 执行某种批量插入(例如加载数据帧或从文件加载)应该比为每一行构造单独的插入更快。

标签: python sql database performance insert


【解决方案1】:

你试过cursor.executemany(...)而不是cursor.execute(...)吗?

您也可以简单地添加cursor.fast_executemany = True 来提高executemany 的性能。 更多信息请参考here。

或

如果您想使用 pandas 进行尝试。 试试这个:

import sqlalchemy
import os
import pandas as pd
engine = sqlalchemy.create_engine("<Dialect>",isolation_level="AUTOCOMMIT")

for file in Path("/path/to/folder").iterdir():
    with open(file,mode='r' as file_open:
              results.append(file_open.read())
df=pd.DataFrame(results)
df.to_sql(table,engine,index=False,if_exists="append")

方言或 DBAPI (See here)。

有关性能改进的更多信息,请点击here。

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多