Reputation: 103
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()
Upvotes: 3
Views: 3873
Reputation: 65228
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()
Upvotes: 0
Reputation: 31646
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)
Upvotes: 4