Get source SQL query from prepared statement in SQLite

I am using SQLite (3.6.4) from a C ++ application (using standard C api). My question is: once the query has been prepared using sqlite3_prepare_v2() and related to the parameters using sqlite3_bind_xyz() - is there a way to get the row containing the original SQL query?

The reason is that something went wrong, I would like to print the request (for debugging, this is my own test application for developers).

Example:

 sqlite3_prepare_v2(db, "SELECT * FROM xyz WHERE something = ? AND somethingelse = ?", -1, &myQuery, NULL); sqlite3_bind_text(myQuery, 1, mySomething); sqlite3_bind_text(myQuery, 2, mySomethingElse); // .... // somewhere else, in another function perhaps if (sqlite3_step(myQuery) != SQLITE_OK) { // Here i'd like to print the actual query that failed - but I // only have the myQuery variable exit(-1); } 

Bonus points if they can also print the actual parameters that were related. :)

+6
c ++ sqlite
source share
3 answers

According to the comments in sqlite3.c (concatenation) sqlite3_sql (myQuery) will return the SQL source.

I do not see any function for determining the binding of a value at a specific index, but we can easily add it to the standard set of SQLite functions. It might look something like this:

 const char* sqlite3_bound_value(sqlite3_stmt* pStmt, int index) { Vdbe *p = (Vdbe *)pStmt; // check if &p->aVar[index - 1] points to a valid location. return (char*)sqlite3ValueText(&p->aVar[index - 1], SQLITE_UTF8); } 

Well, the above code only shows a possible way to implement sqlite3_bound_value (). I have not tested it, it may be wrong, but it gives some tips on how and where to start.

+3
source share

You might want to use sqlite3_trace

This will call the callback function (which you define), and the parameter is the char * SQL of prepared statements (including related parameters).

+4
source share

Indication of documentation:

In the v2 interfaces, the prepared statement that is returned (sqlite_stmt object) contains a copy of the SQL source text.

http://www.sqlite.org/c3ref/prepare.html

+1
source share

All Articles