1

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

3
  • The second form should work. Can you confirm what the error message is for the second form specifically? The example only shows the error for the first form. Commented Nov 7, 2015 at 12:28
  • Did you try cursor.execute("SHOW columns from (%s)", ['students'])? Commented Nov 7, 2015 at 12:48
  • the error from the 2nd one: Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> cursor.execute("SHOW columns from %s", ('students',)) File "C:\Anaconda\lib\site-packages\MySQLdb\cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "C:\Anaconda\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue 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 ''students'' at line 1") Commented Nov 7, 2015 at 18:57

2 Answers 2

1

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

cursor.execute("SHOW columns from {}".format('students'))
Sign up to request clarification or add additional context in comments.

1 Comment

probably because in my case there's only argument, whereas in yours there're 2 and the 2nd one is treated as the 2nd argument passed to cursor.execute()
0
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.