Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

Using a python variable in a sql statement

Help
Rich
2010-06-14
2012-09-19
  • Rich
    Rich
    2010-06-14

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

    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
    wrong

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

    Thanks!!

     
  • 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)