所以我目前正在将 Python 与 SQL 连接起来以提取客户信息。不幸的是,我遇到了一些关于 SQL 的错误。我正在尝试使用 LIKE 运算符和 % 通配符,但我不断收到错误,因为 Python 不喜欢 %。结果,它假装 %s 之间的变量不存在。这就是我的意思:
SELECT custnbr,
firstname,
middleint,
lastname
FROM lqppcusmst
WHERE custnbr = ? AND firstname LIKE ?
现在,我只是在测试它,所以我只使用客户编号和名字。我给它一个值:
remote_system_account_number = request.DATA['remote_system_account_number']
remote_system_first_name = request.DATA['remote_system_first_name']
由于我写的是在数据库中搜索客户,所以可能会有空白条目,所以我这样写:
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%"
所以我认为这会奏效,但事实并非如此。当我这样执行时:
database_cursor.execute(customer_information_SQLString + SQL_where, parameters)
我明白了:
ProgrammingError: ('The SQL contains 2 parameter markers, but 1 parameters were supplied', 'HY000')
有人知道怎么处理吗?
最佳答案
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%")
关于python - PYODBC 不喜欢 %, "The SQL contains 2 parameter markers, but 1 parameters were supplied.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24373806/