简体   繁体   English

我可以在 sqlite3 中为表名使用参数吗?

[英]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.我对 sqlite3参数有一些奇怪的感觉,我想向您展示。

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 .感觉表名不能使用sqlite参数,但是在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?在准备查询之前,我是否必须预处理我的 SQL 语句以包含表名?

Ooookay, should have looked more thoroughly on SO. Ooookay,应该对 SO 进行更彻底的研究。

Answers:答案:
- SQLite Parameters - Not allowing tablename as parameter - SQLite 参数 - 不允许表名作为参数
- Variable table name in sqlite - sqlite 中的变量表名称

They are meant for Python, but I guess the same applies for C++.它们适用于 Python,但我想这同样适用于 C++。

tl;dr : tl;博士

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.如果有人在 SQLite 文档中有我对此进行确认的链接,我将很乐意接受答案。

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++:我知道这已经很老了,但是由于您的查询只是一个字符串,因此您始终可以 append 在 C++ 中像这样的表名:

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

or in objective-C:或在 objective-C 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM