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