python - PYODBC 不喜欢 %, "The SQL contains 2 parameter markers, but 1 parameters were supplied."

标签 python sql pyodbc

所以我目前正在将 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/

相关文章:

python - 如何在 Selenium 和 Python 中使用类型查找元素

mysql - 从 Ruby 中的表中获取所有值

python - 在 Ubuntu VM 中运行 python3 文件时无法打开 lib 'SQL Server Native Client 11.0'

python - 我无法理解奇怪的行为

python - Pandas 映射列

php - 使用 mysql 返回 2 个日期之间的特定元素

sql - 在 Postgresql 中,对两列的组合强制唯一

python - 无法打开库 'ODBC Driver 13 for SQL Server' ?符号链接(symbolic link)问题?

python - pyodbc.尝试打开jet数据库时出错

python - Kubernetes部署,如何解决: psycopg2. OperationalError : SCRAM authentication requires libpq version 10 or above?