Python MySQLdb execute table variable [duplicate]

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.

Leave a Comment