Cong Wang
Cong Wang

Reputation: 3

sqlite statement text syntax near?

const char* sqlstr = "select count(id) from ?";

sqlite_prepare_v2(mConn, sqlstr, -1, &smtm, NULL)

function returns error, error msg got from sqlite3_errmsg(mConn); it tips near "?": syntax error why?

select ? from account

will passthrough.

Upvotes: 0

Views: 522

Answers (1)

mvp
mvp

Reputation: 116167

In SQLite (or any other SQL engine for that matter) you can use parametrized variables only as values to insert, update or constrain. You cannot use it in arbitrary parts of your SQL statement instead of keywords, table names, or column names when used as lvalue.

This is because SQLite has to parse your SQL statement and decide how to possibly join it with other tables, which indexes to use and similar decisions which then become query plan.

Dynamically bound variables like in your second example do not change query plan and are ok to use, but changing table names will - and SQLite does not like it at all.

If you really need to dynamically supply table name, you can generate your SQL string dynamically in your code, and then pass that string to SQLite such that table name is already there (not as ?).

Upvotes: 2

Related Questions