簡體   English   中英

將Python字典用於CX_ORACLE的SQL INSERT語句

[英]Using a Python dict for a SQL INSERT statement for 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()

如果您要插入一組已知的列,只需使用帶有命名參數的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)

您可以使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM