首页 > 解决方案 > 尝试在 Python 中从 CSV 导入 Oracle 数据库

问题描述

我是 Python 新手,正在尝试使用 Python 将 excel 工作表内容插入到 oracle 数据库中。

我使用 PowerShell

这是我到目前为止没有任何运气的尝试:

import cx_Oracle
import csv
import sys

cx_Oracle.init_oracle_client(lib_dir=r"C:\Users\User\AppData\Local\Programs\Python\Python39")
connection = cx_Oracle.connect( user="username", password="password", dsn="hostname:port/dbname")
cursor=connection.cursor()
    

with open('c:\oracle\output.csv') as f:

reader=csv.DictReader(f,delimiter=',')
for row in reader:
sqlquery="INSERT INTO table VALUES (%d,'%s','%s','%s')" %(x,row['ORG_NAME'],row['ID'],row['ORGANIZATION_ID'])
cursor.execute(sqlquery)
x=x+1

conn.commit()

Excel 表只有 3 行,虽然我正在做测试。

任何提示将不胜感激。

也试过 csv2db 但总是得到以下错误:

连接到数据库时出错:DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library

当我从 Python 连接到数据库时,我没有收到此错误,但是当我从 Powershell 执行 csv2db 时,我总是收到此错误。

标签: pythonoraclecsvsql-insertcx-oracle

解决方案


如果您想读取 CSV 文件,您可能会比阅读 cx_Oracle 手册Loading CSV Files into Oracle Database更糟糕:

import cx_Oracle
import csv

. . .

# Predefine the memory areas to match the table definition
cursor.setinputsizes(None, 25)

# Adjust the batch size 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()

推荐阅读