python - 尝试在 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 时,我总是收到此错误。
解决方案
如果您想读取 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()
推荐阅读
- informatica - Informatica 开发人员中的可选联合转换
- python - 使用@tf.function 进行自定义张量流训练的内存泄漏
- javascript - 动态删除搜索结果
- css - CSS填充左右div,而中心div具有固定宽度
- python - 获取 cog 中的命令
- node.js - 嵌套的 NestJS 服务器
- java - Java中的线程问题:具有相同优先级的两个线程应该没有“顺序”对吗?
- c# - 我有一个包含 PDF 文件的共享点列表,我想使用 LINQ 通过其 ID 检索文件,如何使用 linq 来执行此操作?
- python - 通过迭代列表、字典和常量来创建字符串
- javascript - 如何检查 Typescript 条件类型中的类型是否未定义?