tags:

views:

1383

answers:

3

I'm writing some c++ code that uses the sqlite3 library. I'm using a prepared statement to which I bind a variable at runtime.

How do I examine the SQL query in the statement after the bindings?

For example, the code below doesn't return a row. When using a premade string and sqlite3_exec, I get the results I expect.

sqlite3_stmt *statement;
const char *query = "SELECT * FROM foo WHERE (name='?');";
sqlite3_prepare_v2(db, query, strlen(query), &statemtnt, NULL);
sqlite3_bind_text(statement, 1, "bar", -1, SQLITE3_STATIC);
int result = sqlite3_step(statement);
// expected: result = SQLITE_ROW
// actual: result = SQLITE_DONE

edit: As Ferdinand stated below, the problem in the query above is the quotes around the ?. However, for the future, I'd still like to know how to inspect the sqlite3_stmt for the actual query that will be executed.

+1  A: 

The third parameter of sqlite3_bind_text is supposed to be the value you want to bind - in your code you are trying to bind the query to itself!

Also, lose the semicolon at the end of the SELECT.

anon
Sorry, had a typo when writing the question.So, no, that's not the real problem, sorry
Gilad Naor
I believe the semi-colon is required
Gilad Naor
+2  A: 

The SQL query does not change after the bindings -- your variables aren't inserted into the SQL string or anything.

In addition to what Neil said, drop the quotation marks around the ? placeholder:

"SELECT * FROM foo WHERE name = ?"

Otherwise SQLite won't replace the question mark but will treat it as the string "?".

Ferdinand Beyer
Thanks, the problem was indeed the quotes around the ?.
Gilad Naor
I know the sql string doesn't change (I declared it const, after all). BUT, the statement changes. Is there any way to see what query will go to the DB after the bindings by looking at the statement?
Gilad Naor
You mean that you want to inspect the parse tree generated by SQLite? I don't think you can do that without digging into the SQLite source code...
Ferdinand Beyer
A: 

Don't know sqlite all that well, but the actual query might be logged or you might be able to flip a switch to get it to be logged.

BubbaT