title: How to get prepared query which is sent to db
body: <p>When using database libraries like <a href="http://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a> that implement the <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">Python Database API Specification</a> how can you get the fully prepared query after parameter substitution has been applied. I'm making a call to a Sybase stored procedure that will receive 18 arguments through parameter substitution. I would like to capture the actual call that was made and log it to help in debugging. A simpler example of what I need:</p>
  
  <p><strong>pyodbc example</strong></p>
  
  <pre><code>import pyodbc
  conn = pyodbc.connect('DSN=test;PWD=password')
  c = conn.cursor()
  c.execute('CREATE TABLE stocks (symbol varchar(10), price real)')
  c.execute("INSERT INTO stocks VALUES (?, ?)", ('RHAT', 35.14))
  c.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT',))
  print c.fetchone()
  </code></pre>
  
  <p><strong>expected final queries (to be logged)</strong></p>
  
  <pre><code>CREATE TABLE stocks (symbol varchar(10), price real)
  INSERT INTO stocks VALUES ('RHAT', 35.14)
  SELECT * FROM stocks WHERE symbol = 'RHAT'
  </code></pre>
  
  <p><strong>sqlite3 example</strong></p>
  
  <pre><code>import sqlite3
  conn = sqlite3.connect(':memory:')
  c = conn.cursor()
  c.execute('CREATE TABLE stocks (symbol text, price real)')
  c.execute("INSERT INTO stocks VALUES (?, ?)", ('RHAT', 35.14))
  c.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT',))
  print c.fetchone()
  </code></pre>
  
  <p>I've put the sqlite3 example as it doesn't need pyodbc to try it out.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>It seems that when one uses <a href="http://en.wikipedia.org/wiki/Prepared_statements" rel="nofollow">prepared statements</a> the process of filling the data into the template is done server side in the DBMS. So frequently there is no method or api to get that final version of the query from the server, as described in user581592's  answer. Other links of note are <a href="http://code.google.com/p/pyodbc/issues/detail?id=163" rel="nofollow">Issue 163</a> on pyodbc that discusses this further. Also some db libraries like psycopg have added a method <a href="http://initd.org/psycopg/docs/cursor.html#cursor.mogrify" rel="nofollow">mogrify</a> that will return the final statement. But as mentioned in their documentation this is not part of the DB API.</p>