How to get a prepared request that is sent to db

When using database libraries such as pyodbc that implement the Python Database API Specification , how can you get a fully prepared query after changing the parameters. I am calling the Sybase stored procedure, which will receive 18 arguments through parameter replacement. I would like to capture the actual call that was made and register it to help with debugging. A simple example of what I need:

pyopbc example

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() 

pending final requests (for registration)

 CREATE TABLE stocks (symbol varchar(10), price real) INSERT INTO stocks VALUES ('RHAT', 35.14) SELECT * FROM stocks WHERE symbol = 'RHAT' 

Sqlite3 example

 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() 

I have attached sqlite3 example since it does not need pyobbc to try it.

UPDATE

It seems that when you use prepared statements , the process of filling in the data in the template is performed on the server side in the DBMS. Therefore, often there is no method or api to get this final version of the request from the server, as described in user581592's answer. Other notes: Issue 163 on pyobbc, which discusses this further. Also, some db libraries, such as psycopg, have added the mogrify method, which will return the final statement. But, as mentioned in their documentation, this is not part of the database API.

+4
source share
1 answer

From https://groups.google.com/forum/#!topic/pyodbc/656mRdbjFuc

pyodbc does not modify SQL in any way. In general, the “good” ODBC drivers also do not work.

Since this is not a supported function, there is no ODBC function to get the final SQL, so pyodbc cannot offer this.

So, it is best to register the queries and arguments separately in your script, or you can try setting up some level of query logging in the database, if possible.

+3
source

Source: https://habr.com/ru/post/1490879/


All Articles