Search code examples
pythonmysqlpymysql

1064: SQL syntax error executing PyMySQL query


I am using PyMySQL to execute SQL query commands from python. My pystyle is pyformat which was found using:

>>> pymysql.paramstyle
pyformat

My db and cursor details are as follows:

>>> MYDB = pymysql.connect(_params_)
>>> cursor = MYDB.cursor()

I then execute a SQL query using,

>>> cursor.execute("SELECT * FROM %(tablename)s",  {"tablename": "activity"})

I get an error stating,

ProgrammingError: (1064, u"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 '''activity''' at line 1")

On the other hand, the query by itself works,

>>> unsafe_sql = ("Select * from activity")
>>> cursor.execute(unsafe_sql)
>>> 4

I am not sure what is going on with my first query. Any help appreciated.


Solution

  • You can't pass a table name as a parameter to cursor.execute(). Whenever a parameter is a string it quotes it when it substitutes into the query. Use a normal string formatting method, e.g.

    cursor.execute("SELECT * FROM %(tablename)s" % {"tablename": "activity"})