首页 > 解决方案 > 使用 cx_Oracle 中 csv 文件中的变量更新数据库

问题描述

在使用 cx_Oracle 和 Python3.6.8 在 Oracle 数据库中执行更新命令时遇到错误ORA-01036: 非法变量名称/编号。

我想使用 CSV 文件 (db_results.csv) 中的变量值并执行更新命令。

db_results.csv 文件如下所示:

id, order_id, product, Courier, state
01, ORD987, Keyboard, DHL, TX
02, ORD976, Charger, Blue Dart, NY

我的代码:

con = cx_Oracle.connect("abc/abc@abc")
cur = con.cursor()

with open(r'D:\db_results.csv') as file:
    next(file)
    for line in file:
        x = line.replace('\n', ' ').replace('\r', '')
        columns = x.split(",")
        y = columns[1]
    SQL = "update inventory set model='301547' where order_id = '?'"
    cur.execute(SQL, y)
    con.commit()
con.close()

在 cx_Oracle 中使用 UPDATE 是否有任何特定语法?试图找到这方面的例子,但到目前为止还没有找到。

标签: pythonpython-3.xpandasoraclecx-oracle

解决方案


  • ORA-01036由于 oracle 的占位符类型错误而引发,而更喜欢使用以冒号开头的整数,例如 :1,:2

  • 不要忘记修剪第二个占位符的值,以消除环绕值的空格y

  • 无需在 DML 中嵌入参数,而是将它们转换为元组,例如(301547, y)

    ...
    with open(r'D:\db_results.csv') as file:
        next(file)
        for line in file:
            x = line.replace('\n', ' ').replace('\r', '')
            columns = x.split(",")
            y = columns[1]
            SQL = "UPDATE inventory SET model=:1 WHERE order_id = TRIM(:2)"
            cur.execute(SQL, (301657, y))
        con.commit()
    con.close()
    

推荐阅读