Python MySQLdb type error while using execute with %s

Question:

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:Anacondalibsite-packagesMySQLdbcursors.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

Asked By: Dimgold

||

Answers:

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

cursor.execute("SHOW columns from {}".format('students'))
Answered By: Incerteza
cursor.execute("SHOW columns from VALUES (%s)", ('students',))

If you have too many variables you may want to break:

sql = "SHOW columns from VALUES (%s)"
values = ('students', 'teachers')
cursor.execute (sql, values)

But if you create a tuple ahead, as on:

sql = "SHOW columns from VALUES (%s)",('students', 'teachers')

You will need:

cursor.execute (sql[0], sql[1])
Answered By: Al Martins