Tapefreak Tapefreak - 1 month ago 7
Python Question

How to display an SQL string that has been constructed by MySQLDB cursor?

I would like to verify for myself how this MySQL string is translated by the cursor:

cursor.execute("SELECT * from elements where id = %s", (element_id))


Is there a way to get at the computed SQL string and print it out, preferably before execution? (the latter is not absolutely necessary - I'm just doing this because I'm learning Python and want to make sure my SQL strings are being sanitized)

Answer

Yes. As Ferdinand has pointed out, there is a MySQLdb/cursors.py containing an execute(), which in turn calls _query().

This puts the executed query into self._executed.

So you can get it from cursor._executed.