python - 使用 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 是否有任何特定语法?试图找到这方面的例子,但到目前为止还没有找到。
解决方案
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()
推荐阅读
- android - 如何检查我的 listview 适配器是否被我的 editext 文本过滤?
- vue.js - 当用户在 Vue 和 Vuex 中从第一条路线转到第二条路线和第二条路线到第一条路线时,想要在第一条路线上运行功能
- python - 为什么 random.uniform(0, float("inf")) 总是返回 inf?
- gulp - 如何让 gulp 同时写入所有文件?
- laravel - 重命名命令后phpunit错误异常?
- kubernetes - 来自服务器的错误(未找到):找不到 deployments.extensions “hello-node-64c578bdf8-jp7dt”
- android - 无法解决“所有 com.android.support 库必须使用完全相同的版本规范”
- laravel - 宅基地中的laravel websocket无法正常工作
- python - 重新打开后,arduino 和 pyserial 之间的串行连接变慢
- android-studio - Android Studio 生成签名包/apk