python - 对 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()
解决方案
如果您有一组已知的要插入的列,只需使用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)
推荐阅读
- reactjs - 当我将我的 react 应用程序部署到 gh-pages 时,为什么我会丢失我的图像?
- python - 如何在不使用 Jupyter 的情况下捕获所有 Python 解释器输出
- excel - 如果下面的单元格上的值为 TRUE,如何突出显示整行?
- r - 在 R 中创建列时尝试应用非函数
- recursion - 如何以递归方式更改字符串,将数字添加到字符串并将每个数字添加到列表中
- python - Python中的未知错误与尝试循环后的代码
- r - 可重复的纵向报告写作
- c# - 如何在不更改文本字体的情况下使用 FontAwesome 图标
- javafx - ParallelCamera NearClip 和 FarClip
- apache-spark - 在 Spark 中处理没有分隔符的文本文件