Python 在数据库查询中使用占位符不会';行不通

Python 在数据库查询中使用占位符不会';行不通,python,mysql,sql,Python,Mysql,Sql,我正在使用Python2.7查询mysql数据库版本5.6.13 这项工作: whichCustomer = str(1934) qry = ("SELECT * FROM customers WHERE customerid = " + whichCustomer) cursor.execute(qry) 该查询也适用于以下情况: qry = ("SELECT * FROM customers WHERE customerid = 1934") cursor.execute(qry) 但是

我正在使用Python2.7查询mysql数据库版本5.6.13

这项工作:

whichCustomer = str(1934)
qry = ("SELECT * FROM customers WHERE customerid = " + whichCustomer)
cursor.execute(qry)
该查询也适用于以下情况:

qry = ("SELECT * FROM customers WHERE customerid = 1934")
cursor.execute(qry)
但是,当我尝试使用字符串替换时,查询失败:

whichCustomer = 1934
qry = ("SELECT * FROM customers WHERE customerid = %d")
cursor.execute(qry, (whichCustomer))
有什么我不知道的吗。完整的try/execute代码如下所示:

try:
    import mysql.connector
    print 'Module mysql initialized'
    print 'Attempting connection to cheer database' 
    cnx = mysql.connector.connect(user='notsure', 
            password='notsure',
            host='localhost',
            database='notreal')
    cursor = cnx.cursor()
    whichCustomer = str(1934)
    qry = ("SELECT * FROM customers WHERE customerid = " + whichCustomer)
    cursor.execute(qry)
    recx = cursor.fetchone()
    print recx[1]
    cnx.close()
    print 'Successful connection to notreal database'
except:
    print 'Error initialzing mysql databsasr'

SQL参数需要使用
%s
,第二个参数必须是一个序列,如元组:

whichCustomer = 1934
qry = ("SELECT * FROM customers WHERE customerid = %s")
cursor.execute(qry, (whichCustomer,))
注意第二个参数中的逗号;如果没有逗号,则该参数不是元组,而是只传入
1934
整数值


尽管Python字符串插值占位符和SQL参数都使用密切相关的语法,但它们不是一回事。因此,无论类型如何,位置值的SQL参数始终表示为
%s

确保准确报告“不起作用”的内容:如果出现错误,则应包括消息。