0

所以我目前正在编译一个简单的 SQL 查询,如下所示:

    const char *sqlQuery = "SELECT value FROM settings WHERE name=? LIMIT 1";

    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlQuery, -1, &compiledStatement, nil) == SQLITE_OK)
    {
        sqlite3_bind_text(compiledStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);

        while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        {
            NSString *theValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

            // ...
        }
    }

但是我希望能够更改我正在调用的表名。我想我可以将 sqlQuery 更改为:

const char *sqlQuery = "SELECT value FROM ? WHERE name=? LIMIT 1";

然后在绑定名称值之前绑定它,但是这不起作用。我想这仅适用于选择参数...

有谁知道是否有办法在此处插入表名,还是我只需要以纯文本形式进行?

4

2 回答 2

1
NSString *queryString = [NSString stringWithFormat:@"SELECT value FROM %@ WHERE name=%@ LIMIT 1",tablename,attribute];

 const char *sqlQuery = [queryString UTF8String];

希望这可以帮助..

于 2013-04-08T14:01:08.600 回答
1
 NSString *sqlTemplate = @"SELECT value FROM %@ WHERE name=? LIMIT 1";

 //assuming you have your table name stored in tableName variable
const char *sqlQuery = [[NSString stringWithFormat:sqlTemplate, tableName] UTF8String];

sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database, sqlQuery, -1, &compiledStatement, nil) == SQLITE_OK)
{
    sqlite3_bind_text(compiledStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);

    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
    {
        NSString *theValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

        // ...
    }
}
于 2013-04-08T14:10:45.597 回答