oracle Python/SQL插入到缺少的表达式

vxf3dgd4  于 2023-08-03  发布在  Oracle
关注(0)|答案(2)|浏览(130)

使用Python,尝试将一行值写入SQL表。值(n=27)是数据类型(text、int、date)的混合,并且使用定制构建的函数来执行对SQL表的事务。我有一个字段列表:

oracleFieldsList = ["REQ_ID", "MEMBER_ID", "DATA_ID", "DTTM_REQ", "DTTM_UPD", "DESCR_PROJECTION", "DESCR_LOCATION", "MEDIA_TRANSFER",
"FILE_FORMAT", "TAX_SUPPORTED", "REQ_NOTES", "USER_PROJECT", "DTTM_STAFF", "STAFF_ID", "DTTM_DELIVER", "FILE_SIZE", "SIZE_TYPE",
"NO_FILES", "DTTM_CANCEL", "CANCEL_BY_ID", "DWNLD_URL", "LABOR_HOURS", "LABOR_TOTAL", "MEDIA_QUANT", "MEDIA_TOTAL", "INVOICE_DATE", "ADMIN_ID"]
oracle_fields = ",".join(oracleFieldsList)

字符串
以及存储一行的值的变量列表:

entryValuesList = [str(REQ_ID), MEMBER_ID, DATA_ID, str(DTTM_REQ), str(DTTM_UPD), str(DESCR_PROJECTION), DESCR_LOCATION, MEDIA_TRANSFER,
str(FILE_FORMAT), TAX_SUPPORTED, REQ_NOTES, str(USER_PROJECT), DTTM_STAFF, STAFF_ID, DTTM_DELIVER, FILE_SIZE, SIZE_TYPE,
NO_FILES, DTTM_CANCEL, CANCEL_BY_ID, DWNLD_URL, LABOR_HOURS, LABOR_TOTAL, MEDIA_QUANT, MEDIA_TOTAL, INVOICE_DATE, ADMIN_ID]
entry_values = ",".join(entryValuesList)


然后执行事务,其中:

cmd = "INSERT INTO PERSONS (" + oracle_fields + """) VALUES\
        (""" + entry_values + ")"

def updateDatabase(query):
    try:    
        import cx_Oracle
        print(query)

        #submit query
        connstr = 'XXXXXXX'
        conn = cx_Oracle.connect('XX', 'XXX', connstr)
        curs = conn.cursor()
        curs.execute(query)
        conn.commit()
        conn.close()
    except Exception as e:
        print(str(e))

updateDatabase(cmd)


我一直收到“ORA-00936:缺少表达式”或“ORA-00917:缺少逗号”
我已经仔细检查了缺少的逗号,无结尾的括号等,并没有看到任何明显的原因导致这个错误。任何见解都将不胜感激。
谷歌,尝试/错误,阅读其他帖子,等等。

holgip5t

holgip5t1#

我不确定您是如何在注解中得到cmd示例的,但是当我用一些简单的行运行您的代码时,我没有得到字符串列用逗号 Package 的最后一条语句。
(This是一个使用您的代码作为开始的简化示例)

REQ_ID = 23288
MEMBER_ID = ""
MEDIA_TRANSFER = "Network Transfer (FTP)"

oracleFieldsList = ["REQ_ID", "MEMBER_ID", "MEDIA_TRANSFER"]
entryValuesList = [str(REQ_ID), MEMBER_ID, MEDIA_TRANSFER]

oracle_fields = ",".join(oracleFieldsList)
entry_values = ",".join(entryValuesList)

cmd = "INSERT INTO PERSONS (" + oracle_fields + """) VALUES (""" + entry_values + ")"

print(cmd)
# INSERT INTO PERSONS (REQ_ID,MEMBER_ID,MEDIA_TRANSFER) VALUES (23288,,Network Transfer (FTP))

字符串
你要找的是这样的东西?

entry_values = str(entryValuesList).strip("[]")

cmd = "INSERT INTO PERSONS (" + oracle_fields + """) VALUES (""" + entry_values + ")"

print(cmd)
# INSERT INTO PERSONS (REQ_ID,MEMBER_ID,MEDIA_TRANSFER,TAX_SUPPORTED) VALUES ('23288', '', 'Network Transfer (FTP)', 0)

lb3vh1jj

lb3vh1jj2#

更好的方法是使用绑定变量。这消除了潜在的安全问题(SQL注入),并消除了引号、类型转换等问题使用一个简化的示例:

fields_list = ["REQ_ID", "MEMBER_ID", "INVOICE_DATE"]
oracle_fields = ",".join(fields_list)

data = [2154, 1234, datetime.date.today()]
oracle_binds = ",".join(f":{i + 1}" for i in range(len(data)))
cmd = f"INSERT INTO PERSONS ({oracle_fields}) values {oracle_binds})"
cursor.execute(cmd, data)

字符串

相关问题