将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()
答案 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()