tags:

views:

673

answers:

2

I'm using SQLite (3.6.4) from a C++ application (using the standard C api). My question is: once a query has been prepared, using sqlite3_prepare_v2(), and bound with parameters using sqlite3_bind_xyz() - is there any way to get a string containing the original SQL query?

The reason is when something goes wrong, I'd like to print the query (for debugging - this is an in-house developer only test app).

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 it could also print out the actual parameters that was bound. :)

+1  A: 

As per the comments in sqlite3.c (amalgamation), sqlite3_sql(myQuery) will return the original SQL text.

I don't see any function for finding the value bound at a particular index, but we can easily add one to the standard set of SQLite functions. It may 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 shows only a possible way sqlite3_bound_value() could be implemented. I haven't tested it, it might be wrong, but it gives certain hints on how/where to start.

Vijay Mathew
thanks for the reply, I'll give it a try
Isak Savo
this was as far as it was possible to go without doing too much of a hack. I'm accepting as there doesn't seem to be a proper way to do what I originally wanted.
Isak Savo
+1  A: 

Quoting the documentation:

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

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

Amigable Clark Kant