Menu

Using a python variable in a sql statement

Help
Rich
2010-06-14
2018-02-09
  • 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!!

     
  • 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,))
    
     
    • Chao-Lin Cho

      Chao-Lin Cho - 2018-02-09

      Thanks so much. Solved my problem.

       
  • Cat slave

    Cat slave - 2010-06-14

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

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.