sql中的python列表作为参数

2024-06-01 12:04:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在SQL组件中传递一个python整数列表。我已经看了前面的问题,但没有一个能帮我解决错误。以下是我正在做的:

import cx_Oracle
SQL_Components = '''
SELECT /*+ FIRST_ROWS materialize */
    xxx,
    xxx
FROM
    xxx
    INNER JOIN xxx
    INNER JOIN xxx
    INNER JOIN xxx
    INNER JOIN xxx
WHERE
    tpr.tpr_name LIKE 'M39AAA%' AND mml.mml_name IN (%s)
'''

def get_TPM_IDsDict():
    global chosen_lot
    chosen_lot=[]
    print ("Executing: get_TPM_IDsDict")
    f = open("XXX.txt", "r")
    for line in f:
        chosen_lot.append(line.strip())
    chosen_lot = ["'%s'" % x for x in chosen_lot]
    Cursor.execute(SQL_Components % ("','".join(chosen_lot)))

我得到这个错误:

Cursor.execute(SQL_Components % ("','".join(chosen_lot)))
ValueError: unsupported format character ''' (0x27) at index 580

Tags: nameforsqlget错误componentsxxxlot
1条回答
网友
1楼 · 发布于 2024-06-01 12:04:59

考虑{{CD1}}支持的编号参数。另外,确保在cursor.execute的第二个参数中实际传入参数值。不要覆盖你的价值观

在所有Python DB API(cxOracleibm_dbpsycopg2pyodbc等)中,不应引用参数占位符。此外,在Python中,通常避免使用%进行字符串插值,因为它是de-emphasised (not officially deprecated yet)。相反,使用^{}F-strings(Python 3.6+)

SQL_Components = '''
                 SELECT /*+ FIRST_ROWS materialize */
                     xxx,
                     xxx
                 FROM
                     xxx
                     INNER JOIN xxx
                     INNER JOIN xxx
                     INNER JOIN xxx
                     INNER JOIN xxx
                 WHERE
                     tpr.tpr_name LIKE 'M39AAA%' AND mml.mml_name IN ({})
                 '''
# BUILD NUMBERED PLACEDHOLERS WITH enumerate
prms = [":" + str(i+1) for i,_ in enumerate(chosen_lot)] 

# INTERPOLATE WITH str.format
Cursor.execute(SQL_Components.format(", ".join(prms)), chosen_lot)

相关问题 更多 >