首页 > 解决方案 > 对 CX_ORACLE 的 SQL INSERT 语句使用 Python dict

问题描述

cx_Oracle将字典转换为Python中驱动程序的 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()

标签: pythonsqloraclecx-oracle

解决方案


如果您有一组已知的要插入的列,只需使用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)

推荐阅读