How to display the SQL string that was built by the MySQLDB cursor?

I would like to check 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 a calculated SQL string and print it, preferably before execution? (the latter is not absolutely necessary - I just do it because I'm learning Python and want my SQL strings to be sanitized)

+4
source share
2 answers

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

This puts the executed query in self._executed .

So you can get it from cursor._executed .

+6
source

MySQL-Python does nothing special, it simply encodes each argument to prevent SQL injections, and uses the standard Python % operator to replace %s placeholders with encoded arguments.

If you really want to see the result, run the same code as cursor.execute() :

 from MySQLdb.converters import get_codec def prepare_sql(cursor, query, args=None): if args is not None: query = query % tuple(( get_codec(a, cursor.encoders)(db, a) for a in args )) return query 

See the definition of execute() starting at line 168 in MySQLdb/cursors.py .

+1
source

All Articles