Search code examples
pythonmysqlpython-3.xpymysql

Pymysql table name from variable


I am using Python3 and PyMySQL 0.7.9. Version of Mysql is 5.5.57.

Using this query to fetch data from Mysql works:

cur.execute('SELECT date FROM Tablename1 ORDER BY id DESC LIMIT 1')

I would like to get name of table from variable. Reading Pymysql docs and this Stackoverflow post lead me to belive that this code should work:

dbtable = Tablename1
query = 'SELECT date FROM %s ORDER BY id DESC LIMIT 1'
cur.execute(query, (dbtable, ))

But this results in error:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Tablename1' ORDER BY id DESC LIMIT 1' at line 1")

I also tried using quotes but got different error:

query = 'SELECT `date` FROM `%s` ORDER BY `id` DESC LIMIT 1'
cur.execute(query, (dbtable, ))

Results in:

pymysql.err.ProgrammingError: (1146, "Table 'Databasename.'Tablename1'' doesn't exist")

How should the query be changed to allow variable work?


Solution

  • Like this :

    dbtable = input("Table name: ")
    query = "SELECT * FROM %s"%(dbtable)
    cur.execute(query)
    
    results = cur.fetchall()
    
    for row in results:
    print (row[0], row[1], row[2], row[3])