Sqlite_binding方法

时间:2012-08-10 11:52:31

标签: objective-c

如何在不使用stringWithFormat的情况下编写此查询。如何将参数传递给SQLite查询。现在我的代码是这样的:

NSString *querySQL = [NSString stringWithFormat:@"SELECT name, char_code, sound, status  From Tmy_table Where ID=\"%d\"", i];

提前致谢

2 个答案:

答案 0 :(得分:1)

NSString sql = @"SELECT name, char_code, sound, status  From Tmy_table Where ID=?";
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, SQLITE_STATIC) == SQLITE_OK)
{
    // If 'i' was text:
    // if (sqlite3_bind_text(stmt, 1, i, -1, SQLITE_STATIC) == SQLITE_OK)
    if (sqlite3_bind_int(stmt, 1, i) == SQLITE_OK) // Note: 1-based column when binding!!!!
    {
        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            const char *name = sqlite3_column_text(stmt, 0); // Note: 0-based column when fetching!!!
            const char *sound = sqlite3_column_text(stmt, 1);
            const char *status = sqlite3_column_text(stmt, 2);
            // ... print the values or whatever
        }
    }
    else
    {
        NSLog(@"Failed to bind int: %s", sqlite3_errmsg(database));
    }
    sqlite3_finalize(stmt);
}
else
{
    NSLog(@"Failed to prepare statement '%@': %s", sql, sqlite3_errmsg(database));
}

编辑将绑定更改为sqlite3_bind_text(),因为i似乎是文字...

答案 1 :(得分:1)

您应该使用sqlite3主机参数和sqlite3_bind()将变量绑定到它们。在你的例子中,这就像这样。

NSString* query = @"SELECT name, char_code, sound, status  From Tmy_table Where ID=?";
sqlite3_stmt* myStatement = NULL;
sqlite3_prepare_v2(myDBConnection, [query UTF8String], -1, &myStatement, NULL);
sqlite3_bind_int(myStatement, 1, i);

注意事项:

  • 两个sqlite3函数返回必须检查的错误代码。为了清楚起见,我已将其留下了。
  • sqlite3_bind_int()中的第二个参数告诉您要用第三个参数替换哪个问题mar。索引从1开始,而不是0。

另见docs about binding