+2  A: 

When executing a prepared statement, no new SQL is generated. The idea of prepared statements is that the SQL query and its data are transmitted separately (that's why you don't have to escape any arguments) - the query is most likely only stored in an optimized form after preparing it.

ThiefMaster
Ah! Thank you. I didn’t know that was how it worked. Makes sense :)
Ben Hodgson
+1  A: 

Hi Ben,

when you create a prepared statement, the "template" SQL code is sent to the DBMS already, which compiles it into an expression tree. When you pass the values, the corresponding library (python sqlite3 module in your case) doesn't merge the values into the statement. The DBMS does.

If you still want to produce a normal SQL string, you can use string replace functions to replace the placeholders by the values (after escaping them).

What do you need this for?

chiccodoro
Unfortunately I need to generate sqlite–compatible SQL to pass to another application. I was hoping to use something like sqlite3 or sqlalchemy to do all the escaping etc.
Ben Hodgson
In that case I think the approach with escaping and replacing with string operations could be appropriate. Is the prepared statement also created for SQLite? If not, you might need to transform some expressions from the other DB's dialect to SQLite's dialect. In Java, hibernate provides classes to generate dialect-specific expressions. I'm not sure whether it would provide functions to "degenerate" dialect-specific expressions for transforming them into another dialect, and I don't know how it is implemented in sqlalchemy.
chiccodoro