Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use parameters for the table name in sqlite3?

Tags:

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, 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?

like image 998
Gui13 Avatar asked May 03 '11 13:05

Gui13


People also ask

Can table name be parameterized?

No, a parameterised query doesn't just drop the parameter values in to the query string, it supplies the RDBMS with the parameterised query and the parameters separately. But such a query can't have a table name or field name as a parameter.

How do I find the table name in SQLite?

So to get a list of all tables in the database, use the following SELECT command: SELECT name FROM sqlite_schema WHERE type='table' ORDER BY name; For indices, type is equal to 'index', name is the name of the index and tbl_name is the name of the table to which the index belongs.

Does SQLite support parameterized query?

SQLite doesn't support output parameters. Return values in the query results instead.


2 Answers

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.

like image 166
Gui13 Avatar answered Sep 18 '22 13:09

Gui13


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];
like image 32
PirateDave Avatar answered Sep 21 '22 13:09

PirateDave