在iPhone上从SQLite3获取数据时出现问题

时间:2010-02-12 17:12:45

标签: iphone xcode sqlite

我一直试图在已经访问过两个表之前从表中返回数据,但是在这种情况下它会进入while语句,但不会分配任何值,因为所有内容都设置为null。

代码是:

NSMutableArray *all_species = [[NSMutableArray alloc] init];
sqlite3 *db_species;
int dbrc_species;
Linnaeus_LiteAppDelegate *appDelegate = (Linnaeus_LiteAppDelegate*) [UIApplication sharedApplication].delegate;
const char* dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String];
dbrc_species = sqlite3_open (dbFilePathUTF8, &db_species);
if (dbrc_species) {
    return all_species;
}
sqlite3_stmt *dbps_species;
const char *queryStatement = "SELECT species_id, species_name, species_latin, species_genus FROM \
                                linnaeus_species;";
if (sqlite3_prepare_v2 (db_species, queryStatement, -1, &dbps_species, NULL) == SQLITE_OK) {
    sqlite3_bind_int(dbps_species, 1, [the_species_id intValue]);
    while (sqlite3_step(dbps_species) == SQLITE_ROW) {
        Species *species = [[Species alloc] init];
        NSLog(@"%@", sqlite3_column_int(dbps_species, 0));
        [species setSpecies_id:[[NSNumber alloc] initWithInt:sqlite3_column_int(dbps_species, 0)]];
        char *new_name = (char *) sqlite3_column_text(dbps_species, 1);
        [species setSpecies_name:nil];
        if (new_name != NULL) {
            [species setSpecies_name:[NSString stringWithUTF8String:(char *) sqlite3_column_text(dbps_species, 1)]];
        }
        char *new_latin = (char *) sqlite3_column_text(dbps_species, 2);
        [species setSpecies_latin:nil];
        if (new_latin != NULL) {
            [species setSpecies_latin:[NSString stringWithUTF8String:(char *) sqlite3_column_text(dbps_species, 2)]];
        }
        [species setSpecies_genus:[NSNumber numberWithInt:sqlite3_column_int(dbps_species, 3)]];

        [species setEdited:0];
        [all_species addObject:species];
        [species release];
    }
    sqlite3_finalize(dbps_species);
}
else {
    sqlite3_close(db_species);
}

我也尝试过使用NSLog(@“Data:%@”,sqlite3_column_text(dbps_species,1));它会导致EXC_BAD_ACCESS错误,这表明它可能与内存有关,但我看不出原因。

2 个答案:

答案 0 :(得分:3)

NSLog(@"Data: %@", sqlite3_column_text(dbps_species, 1));

会导致EXC_BAD_ACCESS,因为sqlite3_column_text的结果是C字符串(char*),而不是NSString*。要打印C字符串,您需要%s格式说明符:

NSLog(@"Data: %s", sqlite3_column_text(dbps_species, 1));

另外,不要浪费时间两次致电sqlite3_column_text,例如

    char *new_name = (char *) sqlite3_column_text(dbps_species, 1);
    [species setSpecies_name:nil];
    if (new_name != NULL) {
        [species setSpecies_name:[NSString stringWithUTF8String:new_name]];
    }

答案 1 :(得分:0)

您也可以尝试使用FMDB类。这些使得使用sqlite变得更容易。

http://gusmueller.com/blog/archives/2008/03/fmdb_for_iphone.html