14

I'm trying to use a variable for a table name. I get the error "... near ''myTable'' at line 1 I must not be escaping this right. The double '' in the error seems to be a clue, but I don't get it.

db = MySQLdb.connect("localhost","user","pw","database" )
table = "myTable"
def geno_order(db, table):
    cursor = db.cursor() # prepare a cursor object using cursor() method
    sql = "SELECT * FROM %s"
    cursor.execute(sql, table)
    results = cursor.fetchall()
mechanical_meat
  • 155,494
  • 24
  • 217
  • 209
Jim Smith
  • 387
  • 3
  • 9
  • I am sure there are several duplicates. I picked the one I knew, but if someone else finds one that is even more like the OP's problem by all means use it instead. – mechanical_meat Mar 06 '13 at 19:03

1 Answers1

17

You can't use a parameter for the table name in the execute call. You'll need to use normal Python string interpolation for that:

sql = "SELECT * FROM %s" % table
cursor.execute(sql)

Naturally, you'll need to be extra careful if the table name is coming from user input. To mitigate SQL injection, validate the table name against a list of valid names.

davidism
  • 110,080
  • 24
  • 357
  • 317
Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
  • cursor.execute("INSERT INTO {0}(var_name)VALUES({1});".format('table_name','"value"')) #if you need to insert more variables – X.C. Mar 03 '20 at 04:15