Tapefreak Tapefreak - 1 year ago 69
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download