gpt4 book ai didi

python - 如何使用 Python 向 Oracle 数据库中插入 100 万行?

转载 作者:行者123 更新时间:2023-12-02 14:51:42 43 4
gpt4 key购买 nike

我有大约 100,000 到 1,000,000 行要插入到 Oracle18c 数据库中。我对 Oracle 和这个数量级的数据还很陌生。我认为一定有一些最佳的方法来做到这一点,但现在我只能设法实现逐行插入:

def insertLines(connection, table_name, column_names, rows):
cursor = connection.cursor()
if table_exists(connection, table_name):
for row in rows:
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, column_names, row)
cursor.execute(sql)
cursor.close()

在 Oracle 中是否有一些明确的方法来使用 cx_Oracle(python Oracle 库)来批量处理行以达到更高的效率?

编辑:我从 CSV 文件中读取数据。

最佳答案

如果您的数据已经在 Python 中,则使用 executemany() .在您有这么多行的情况下,您可能仍会执行多次调用以插入成批记录。

更新:参见 cx_Oracle 文档 Batch Statement Execution and Bulk Loading .

更新 2:最新版本的 cx_Oracle(已重命名为 python-oracledb)默认以绕过 Oracle 客户端库的“精简”模式运行。这意味着在许多情况下,数据加载速度更快。 executemany() 的用法和功能在新版本中仍然相同。使用类似 python -m pip install oracledb 的方式进行安装。这是 Executing Batch Statement and Bulk Loading 的当前文档.另见 upgrading documentation .

这是一个使用 python-oracledb 命名空间的示例。如果您仍然使用 cx_Oracle,则将 import 更改为 import cx_Oracle as oracledb:

import oracledb
import csv

...
Connect and open a cursor here...
...

# Predefine the memory areas to match the table definition.
# This can improve performance by avoiding memory reallocations.
# Here, one parameter is passed for each of the columns.
# "None" is used for the ID column, since the size of NUMBER isn't
# variable. The "25" matches the maximum expected data size for the
# NAME column
cursor.setinputsizes(None, 25)

# Adjust the number of rows to be inserted in each iteration
# to meet your memory and performance requirements
batch_size = 10000

with open('testsp.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
sql = "insert into test (id,name) values (:1, :2)"
data = []
for line in csv_reader:
data.append((line[0], line[1]))
if len(data) % batch_size == 0:
cursor.executemany(sql, data)
data = []
if data:
cursor.executemany(sql, data)
con.commit()

正如其他人所指出的:

  • 避免在语句中使用字符串插值,因为它存在安全风险。这通常也是一个可扩展性问题。使用绑定(bind)变量。在需要对列名称等内容使用字符串插值的地方,请确保对所有值进行清理。
  • 如果数据已经在磁盘上,那么使用 SQL*Loader 或 Data Pump 之类的工具比将其读入 cx_Oracle 然后将其发送到数据库要好。

关于python - 如何使用 Python 向 Oracle 数据库中插入 100 万行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55271615/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com