PYODBC does not like %, “The SQL contains 2 parameter markers, but 1 parameters were supplied.”

一个人想着一个人 提交于 2019-12-10 17:24:47

问题


So I'm currently linking Python with SQL to pull out customer information. Unfortunately, I'm getting some errors with regards to SQL. I am trying to use the LIKE operator, and the % wildcard, but I keep getting errors because Python does not like %. As a result, it pretends that variable between the %s do not exist. Here's what I mean:

SELECT custnbr,
       firstname,
       middleint,
       lastname
FROM   lqppcusmst
WHERE  custnbr = ?  AND firstname LIKE ? 

Right now, I'm just testing it out, so I'm just using the customer number, and the first name. I give it a value:

remote_system_account_number = request.DATA['remote_system_account_number']
remote_system_first_name = request.DATA['remote_system_first_name']

Since what I'm writing is for searching customers within the database, there's a chance there could be blank entries, so I have it like such:

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%"

So I thought this would work, but it didn't. When I execute it like such:

database_cursor.execute(customer_information_SQLString + SQL_where, parameters)

I get this:

ProgrammingError: ('The SQL contains 2 parameter markers, but 1 parameters were supplied', 'HY000')

Anyone know how to deal with this?


回答1:


parameters should not be a comma separated string, it should be an enumerable (a list or similar) with a number of values matching the number of placeholders in your SQL. For instance:

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%")


来源:https://stackoverflow.com/questions/24373806/pyodbc-does-not-like-the-sql-contains-2-parameter-markers-but-1-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!