Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite prepared statements - how to debug

Tags:

c++

sqlite

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.

like image 444
Gilad Naor Avatar asked Feb 24 '09 09:02

Gilad Naor


People also ask

Does SQLite support prepared statements?

For prepared SQLite statements in Android there is SQLiteStatement. Prepared statements help you speed up performance (especially for statements that need to be executed multiple times) and also help avoid against injection attacks.

What are prepared statements in SQLite?

A prepared statement object is the compiled object code. All SQL must be converted into a prepared statement before it can be run. The life-cycle of a prepared statement object usually goes like this: Create the prepared statement object using sqlite3_prepare_v2().


1 Answers

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 "?".

like image 150
Ferdinand Beyer Avatar answered Oct 18 '22 14:10

Ferdinand Beyer