【问题标题】:Trying to import from CSV to Oracle Database in Python尝试在 Python 中从 CSV 导入 Oracle 数据库
【发布时间】:2021-09-20 05:01:40
【问题描述】:

我是 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 时,我总是收到此错误。

【问题讨论】:

  • 请Edit您的问题正确缩进您的代码。
  • 感谢您的照顾。抱歉,这是我第一次在这里发帖。
  • 我不明白你的问题是什么。如果您没有收到错误消息,那么问题是什么?如果它没有插入数据,那么也许检查你是否真的运行代码。你应该宁愿使用execute(query, values) 而不是使用% 来生成SQL
  • 什么是csv2db?这是使用 Oracle 或 Python 脚本安装的某个程序吗?错误可能意味着您必须安装一些程序,并且它必须是 64 位版本,而不是 32 位版本。
  • 安装 Oracle Instant Client 时,请确保将 sqlplus 添加到组合中。在 Powershell 中,确保您可以启动 sqlplus 并连接到数据库。我的意思是,您需要修复 PS 环境问题“找不到客户端库”。从那里开始你做一个测试:PS C:\>python -c "import cx_Oracle"。当您的环境正确时,csv2db 将起作用。

标签: python oracle csv sql-insert cx-oracle


【解决方案1】:

如果你想读取 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()

【讨论】:

  • 用“没有用”等详细信息更新您的问题,我们会提供帮助。
  • 认为我将采取不同的方式,我将使用 SQL Developer 导入 CSV
  • 我建议使用 Oracle 的 SQL*Loader,它专为加载数据任务而设计,并且有多种选项可以非常快速地完成此任务。它作为 Oracle Instant Client 的一部分免费提供。
猜你喜欢
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
相关资源
最近更新 更多