Using a python variable in a sql statement

  • Rich

    Rich - 2010-06-14

    Suppose I've connected to the server and I want to execute a couple of

    Lets say im connected to a database with a table called People.

    People has the columns Age, Name, Height, and Weight.

    conn = MySQLdb.connect(host = ......)

    cursor1 = conn.cursor()

    myName = 'Bob'

    The query I want to execute is as follows. But I get an error when I run

    this. How do I use something that i've done in python inside my queries
    without getting errors?

    cursor1.execute('''SELECT * FROM People WHERE Name = myName''')

    I have also tried:

    cursor1.execute('''SELECT * FROM People WHERE Name ='''+myName)

    cursor1.execute("SELECT * FROM People WHERE Name = '"+str(myName) + "'")

    cursor1.execute("'SELECT * FROM People WHERE Name ='" + str(myName) + "'")

    cursor1.execute("'select * from People where Name ='" +"'"+str(myName)+"'")

    I was advised to use escape quotes which I tried but my syntax was probably

    Any help would be appreciated. I feel very limited using mysqldb without being
    able to execute queries that use globally defined variables.


  • Kyle VanderBeek

    Kyle VanderBeek - 2010-06-14

    You want to use %s to hold places for your arguments, and then pass a tuple of
    arguments as the second argument to execute:

    cursor1.execute("SELECT * FROM People WHERE Name=%s", (myName,))
  • Cat slave

    Cat slave - 2010-06-14

    cursor1.execute('SELECT * FROM People WHERE Name=%s', myName)


Log in to post a comment.