在数据库查询中使用占位符不起作用

时间:2014-01-01 23:58:26

标签: python mysql sql

我使用python 2.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'

1 个答案:

答案 0 :(得分:2)

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

whichCustomer = 1934
qry = ("SELECT * FROM customers WHERE customerid = %s")
cursor.execute(qry, (whichCustomer,))

注意第二个参数中的逗号;如果没有逗号,那么该参数不是一个元组,只会传入1934整数值。

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