2014-06-23 22 views
4

因此,我目前正在將Python與SQL連接以提取客戶信息。不幸的是,我收到了一些關於SQL的錯誤。我正在嘗試使用LIKE運算符和%通配符,但由於Python不喜歡%,所以我一直在收到錯誤。因此,它假裝%s之間的變量不存在。這就是我的意思:PYODBC不喜歡%,「SQL包含2個參數標記,但提供了1個參數。」

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') 

任何人知道如何面對呢?

+1

嘗試使用'%%'來轉義您的'%'符號。 – BrenBarn

回答

4

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%") 
相關問題