python - 将 Python 字典用于 CX_ORACLE 的 SQL INSERT 语句

标签 python sql oracle cx-oracle

为 Python 中的 cx_Oracle 驱动程序将字典转换为 SQL 插入

custom_dictionary= {'ID':2, 'Price': '7.95', 'Type': 'Sports'}

我需要从自定义字典为 cx_Oracle 驱动程序制作动态代码 sql 插入

con = cx_Oracle.connect(connectString)
cur = con.cursor()
statement = 'insert into cx_people(ID, Price, Type) values (:2, :3, :4)'
cur.execute(statement, (2, '7.95', 'Sports'))
con.commit()

最佳答案

如果您有一组已知的要插入的列,只需使用带有命名参数的 insert 并将字典传递给 execute() 方法。

statement = 'insert into cx_people(ID, Price, Type) values (:ID, :Price, :Type)'

cur.execute(statement,custom_dictionary)

如果列是动态的,使用键和参数构造insert语句 把它放到一个类似的execute

cols  = ','.join( list(custom_dictionary.keys() ))
params= ','.join( ':' + str(k) for k in list(custom_dictionary.keys()))
statement = 'insert into cx_people(' + cols +' ) values (' + params + ')'
cur.execute(statement,custom_dictionary)

关于python - 将 Python 字典用于 CX_ORACLE 的 SQL INSERT 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56624593/

相关文章:

python - 为什么不在 PyPI 上使用 setup.py 元数据?

c# - 将所有列与所有搜索词组匹配

sql - 如何强制oracle在不删除/重新创建约束的情况下进行级联删除

java - 如何在 JDeveloper 的日志记录控制台中显示希腊字符

mysql - 创建表,其中主键是两个不同表中两个字段的组合

oracle - ORA-24247: 发送电子邮件 oracle 时网络访问被访问控制列表 (ACL) 拒绝

Python 3 : how to tests exceptions within with?

python - 事件前后的 Pandas Dataframe 列编码 - 时间序列

python - 使用另一个数据帧替换数据帧中的空值

php - 您的 SQL 语法有误;查看与您的 MySQL 服务器对应的手册