尝试在python中从csv导入oracle数据库

wfveoks0  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(435)

我是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:找不到64位oracle客户端库
当我从python连接到数据库时,我没有收到这个错误,但是当我从powershell执行csv2db时,我总是收到这个错误。

hjqgdpho

hjqgdpho1#

如果要读取csv文件,可能比读取cx\U oracle手动将csv文件加载到oracle数据库更糟糕:

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()

相关问题