3

The sqlite3 module allows one to use parameter substitution for queries like so:

import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table lang (name, first_appeared)")
cur.execute("insert into lang values (?, ?)", ("C", 1972))

I'd like to be able to get the "post-substitution" query string. In the example above that would be:

"insert into lang values ('C', '1972')"

Can it be done? There doesn't seem to be a documented means of doing this, but I'd settle for undocumented.

bbayles
  • 4,389
  • 1
  • 26
  • 34
  • Are you "forced" to use post-substitution? If not: https://stackoverflow.com/a/3220028/13871725 – JJ. Dec 26 '21 at 19:57
  • I want the results of the substitution. If I have to actually execute the query to get it, that's fine, but my goal is to get the post-substitution string. – bbayles Dec 26 '21 at 20:00
  • What problem are you going to solve by having this string? – mkrieger1 Dec 26 '21 at 20:01
  • I'm solving the problem of getting the post-substitution query string! – bbayles Dec 26 '21 at 20:03
  • IMHO I think you should use format strings for this one. – JJ. Dec 26 '21 at 20:04
  • I want exactly what the database would execute given the parameters, so Python string substitution isn't going to work. – bbayles Dec 26 '21 at 20:05
  • 2
    There is no string "substitution". Your query is parsed to a _prepared statement_ first and then during request parameters are "bound" to that prepared statement https://www.sqlite.org/c3ref/bind_blob.html as a result no string exists with "substituted" values. Python just hides that in a simplified API – fukanchik Dec 26 '21 at 20:07
  • @mkrieger1 - yes, `set_trace_callback` seems to do the trick. Many thanks! I'll accept this as an answer if you post it. – bbayles Dec 26 '21 at 20:23

0 Answers0