0

I am querying a mysql database version 5.6.13 using python 2.7.

This works:

whichCustomer = str(1934)
qry = ("SELECT * FROM customers WHERE customerid = " + whichCustomer)
cursor.execute(qry)

The query also works:

qry = ("SELECT * FROM customers WHERE customerid = 1934")
cursor.execute(qry)

BUT, when I try to use string substitution the query fails:

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

Is there something I am missing. The full try/execute code follows:

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
  • Make sure you report exactly what "doesn't work": if there is an error, this should include the message. Commented Jan 2, 2014 at 0:19

1 Answer 1

3

You need to use %s for SQL parameters, and the second argument must be a sequence, like a tuple:

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

Note the comma in the second parameter; without a comma, that parameter is not a tuple and just the 1934 integer value is passed in instead.

Although both Python string interpolation placeholders and SQL parameters use closely related syntax, they are not the same thing. As such, SQL parameters for positional values are always expressed as %s regardless of the type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.