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

时间:2019-06-17 04:06:49

标签: 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()

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用pandas.read_json方法通过dataframe对列表转换后的值进行迭代:

import pandas as pd
import cx_Oracle
con = cx_Oracle.connect(connectString)
cursor = con.cursor()
custom_dictionary= '[{"ID":2, "Price": 7.95, "Type": "Sports"}]'
df = pd.read_json(custom_dictionary)

statement='insert into cx_people values(:1,:2,:3)'
df_list = df.values.tolist()
n = 0
for i in df.iterrows():
    cursor.execute(statement,df_list[n])
    n += 1


con.commit()