Skip to main content
 首页 » 编程设计

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

2024年11月24日8mayingbao

为 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)