开发者

Can I use parameters for the table name in sqlite3?

I'm having some strange feeling abour sqlite3 parameters that I would like to expose to you.

This is my query and the fail message :

#query
'SELECT id FROM ? WHERE key = ? AND (userid = '0' OR userid = ?) ORDER BY userid DESC LIMIT 1;'
#error message, fails when calling sqlite3_prepare()
error: 'near "?": syntax error'

In my code it looks like:

// Query is a helper class, at creation it does an sqlite3_preprare()
Query q("SELECT id FROM ? WHERE key = ? AND (userid = 0 OR userid = ?) ORDER BY userid DESC LIMIT 1;");
// bind arguments
q.bindString(1, _db_name.c_str() ); // class member, the table name
q.bindString(2, key.c_str()); // function argument (std::string)
q.bindInt   (3, currentID); // function argument (int)
q.execute();

I have the feeling that I can't use sqlite parameters for the table name开发者_JAVA百科, but I can't find the confirmation in the Sqlite3 C API.

Do you know what's wrong with my query?

Do I have to pre-process my SQL statement to include the table name before preparing the query?


Ooookay, should have looked more thoroughly on SO.

Answers:
- SQLite Parameters - Not allowing tablename as parameter
- Variable table name in sqlite

They are meant for Python, but I guess the same applies for C++.

tl;dr:

You can't pass the table name as a parameter.
If anyone have a link in the SQLite documentation where I have the confirmation of this, I'll gladly accept the answer.


I know this is super old already but since your query is just a string you can always append the table name like this in C++:

std::string queryString = "SELECT id FROM " + std::string(_db_name);

or in objective-C:

[@"SELECT id FROM " stringByAppendingString:_db_name];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜