2017-04-06 84 views
0

我有以下Python代碼:返回在Python中使用SQL語句中的變量時出錯?

cursor = connection.cursor() 


a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123" 
SQLCommand = ("""SELECT * 
       FROM Table 
       WHERE Table.ENUM = ? 
       """, a) 

results = cursor.execute(SQLCommand) 

以下錯誤:

TypeError: string or integer address expected instead of tuple instance 
+0

你用什麼庫連接到你的數據庫?它可能不支持這樣的Prepared Statements。 – Darney

+0

@Darnell馬丁pypyodbc – Ekaterina

+1

我認爲它應該工作:'''一= 「C6DE6778-5956-48D4-BED6-5A2A37BBB123」 SQL = 「SELECT * FROM 表 WHERE Table.ENUM =%s的」 cursor.execute (sql,a)''' –

回答

0

SQLCommand是你的情況的一個元組。 .execute()需要sql語句作爲第一個參數。爲了糾正錯誤,你可以做這樣的事情:

cursor = connection.cursor() 
a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123" 
SQLCommand = """SELECT * 
       FROM Table 
       WHERE Table.ENUM = '%s' 
       """ % a 
results = cursor.execute(SQLCommand) 

或者,您也可以格式化你的SQL語句字符串是這樣的:

SQLCommand = """SELECT * 
        FROM Table 
        WHERE Table.ENUM = '{}' 
        """.format(a) 

或者你可以通過a作爲可選參數到.execute()這樣:

cursor = connection.cursor() 
a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123" 
SQLCommand = """SELECT * 
       FROM Table 
       WHERE Table.ENUM = ? 
      """ 
print(SQLCommand, a) 

你可以參考the documentation以獲得更多關於此的理解。

+0

你的選項(1)有效 – Ekaterina

3

您構建了SqlCommand的是不正確的方式。當您execute時傳遞參數。

a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123" 
SQLCommand = """SELECT * 
       FROM Table 
       WHERE Table.ENUM = ? 
       """ 

results = cursor.execute(SQLCommand,(a,))