如何在不使用stringWithFormat的情况下编写此查询。如何将参数传递给SQLite查询。现在我的代码是这样的:
NSString *querySQL = [NSString stringWithFormat:@"SELECT name, char_code, sound, status From Tmy_table Where ID=\"%d\"", i];
提前致谢
答案 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);
注意事项: