Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top