PYODBC 不喜欢 %,“SQL 包含 2 个参数标记,但提供了 1 个参数。”

Leo*_*eon 5 python sql pyodbc

所以我目前正在将 Python 与 SQL 联系起来以提取客户信息。不幸的是,我遇到了一些关于 SQL 的错误。我正在尝试使用 LIKE 运算符和 % 通配符,但由于 Python 不喜欢 %. 结果,它假装 %s 之间的变量不存在。这就是我的意思:

SELECT custnbr,
       firstname,
       middleint,
       lastname
FROM   lqppcusmst
WHERE  custnbr = ?  AND firstname LIKE ? 
Run Code Online (Sandbox Code Playgroud)

现在,我只是在测试它,所以我只使用客户编号和名字。我给它一个值:

remote_system_account_number = request.DATA['remote_system_account_number']
remote_system_first_name = request.DATA['remote_system_first_name']
Run Code Online (Sandbox Code Playgroud)

因为我写的是在数据库中搜索客户,所以可能会有空白条目,所以我有这样的:

if remote_system_account_number != '':
    SQL_where += ' custnbr = ? '
    parameters += "remote_system_account_number"
if remote_system_first_name != '':
    SQL_where += ' AND firstname LIKE ? '
    parameters += ", %remote_system_first_name%"
Run Code Online (Sandbox Code Playgroud)

所以我认为这会起作用,但它没有。当我像这样执行它时:

database_cursor.execute(customer_information_SQLString + SQL_where, parameters)
Run Code Online (Sandbox Code Playgroud)

我明白了:

ProgrammingError: ('The SQL contains 2 parameter markers, but 1 parameters were supplied', 'HY000')
Run Code Online (Sandbox Code Playgroud)

有谁知道如何处理这个问题?

Lar*_*tig 5

parameters不应该是逗号分隔的字符串,它应该是一个可枚举的(列表或类似的),其中的值与 SQL 中的占位符数量相匹配。例如:

parameters = []
if remote_system_account_number != '':
    SQL_where += ' custnbr = ? '
    parameters.append("remote_system_account_number")
if remote_system_first_name != '':
    SQL_where += ' AND firstname LIKE ? '
    parameters.append("%remote_system_first_name%")
Run Code Online (Sandbox Code Playgroud)