Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sql

pyodbc

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?

like image 665
Leon Avatar asked Jun 23 '14 19:06

Leon


1 Answers

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%")
like image 133
Larry Lustig Avatar answered Oct 21 '22 18:10

Larry Lustig