简体   繁体   中英

Using a Python dict for a SQL INSERT statement for CX_ORACLE

convert a dictionary to SQL insert for the cx_Oracle driver in Python

custom_dictionary= {'ID':2, 'Price': '7.95', 'Type': 'Sports'}

I'm need making dynamic code sql insert for cx_Oracle driver from custom dictionary

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

If you have a known set of columns to be inserted, simply use the insert with named params and pass the dictionary to the execute() method.

statement = 'insert into cx_people(ID, Price, Type) values (:ID, :Price, :Type)'

cur.execute(statement,custom_dictionary)

If the columns are dynamic, construct the insert statement using the keys and params put it into a similar 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)

You can use pandas.read_json method with iteration over list converted values through 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM