在您致电sqlite3_column_text
时,您使用的索引为1
,但它需要一个从零开始的索引。使用0
而不是1
。见SQLite sqlite_column_XXX
documentation,它说:
结果集的最左边的列的索引为0
顺便说一句,因为stringWithUTF8String
如果你传递一个NULL
值抛出一个异常,在继续之前,如果sqlite3_column_text
不是NULL
,那么检查结果通常更安全,否则将优雅地处理错误。此外,您可能需要检查sqlite3_step
和sqlite3_prepare_v2
错误,像这样:
NSString *queryStatement = [NSString stringWithFormat:@"SELECT ACTIONNAME FROM ACTIONS WHERE ACTIONSYMBOL = '%@'", symbol]; // note, it can be dangerous to use `stringWithFormat` to build SQL; better to use `?` placeholders in your SQL and then use `sqlite3_bind_text` to bind the `symbol` value with the `?` placeholder
if (sqlite3_prepare_v2(database, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
int rc;
while ((rc = sqlite3_step(statement)) == SQLITE_ROW) {
const unsigned char *value = sqlite3_column_text(statement, 0); // use zero
if (value) {
NSString *action = [NSString stringWithUTF8String:(const char *)value];
// now do whatever you want with `action`, e.g. add it to an array or what
} else {
// handle the error (or NULL value) gracefully here
}
// make sure to check for errors in `sqlite3_step`
if (rc != SQLITE_DONE)
{
NSLog(@"%s: sqlite3_step failed: %s", __FUNCTION__, sqlite3_errmsg(database));
}
}
}
else
{
NSLog(@"%s: sqlite3_prepare_v2 failed: %s", __FUNCTION__, sqlite3_errmsg(database));
}
另外,如上述所示,正确执行所有错误检查的是一个有点麻烦。这是FMDB可能是有用的,简化以上(其中db
是已经开了一个FMDatabase
对象):
FMResultSet *rs = [db executeQuery:@"SELECT ACTIONNAME FROM ACTIONS WHERE ACTIONSYMBOL = ?", symbol];
if (!rs) {
NSLog(@"%s: executeQuery failed: %@", __FUNCTION__, [db lastErrorMessage]);
return;
}
while ([rs next]) {
NSString *action = [rs stringForColumnIndex:0];
// do whatever you want with `action` here
}
[rs close];
如果您使用?
占位符(而不是使用stringWithFormat
建立你的SQL,这是危险的)使用FMDB的好处更加引人注目。
来源
2014-02-06 15:55:54
Rob
我建议你使用FMDatabase框架 - 这对于sqlite来说是一个很好的包装。 – etolstoy