Search code examples
pythoncursormysql-pythonexecute

Python MySQLdb type error while using execute with %s


I've started with a simple mysql query in python, returning all the columns of the table. For some reason this command works:

cursor.execute("SHOW columns from students")

While all of the following return a type error:

cursor.execute("SHOW columns from %s", 'students')

cursor.execute("SHOW columns from %s", ('students',))

cursor.execute("SHOW columns from %s", ['students'])

cursor.execute("""SHOW columns from %s""", 'students')

The error is:

Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
    cursor.execute("SHOW columns from %s", 'students')
File "C:\Anaconda\lib\site-packages\MySQLdb\cursors.py", line 187, in   execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

Please advise


Solution

  • Try using format which is a recommended way to format strings:

    cursor.execute("SHOW columns from {}".format('students'))