从iPhone上的SQLite3获取数据时出现问题
我一直试图从一个表返回数据,之前已经访问了两个表,但在本例中,它进入while语句,但没有分配任何值,因为所有内容都设置为null 代码是:从iPhone上的SQLite3获取数据时出现问题,iphone,xcode,sqlite,Iphone,Xcode,Sqlite,我一直试图从一个表返回数据,之前已经访问了两个表,但在本例中,它进入while语句,但没有分配任何值,因为所有内容都设置为null 代码是: NSMutableArray *all_species = [[NSMutableArray alloc] init]; sqlite3 *db_species; int dbrc_species; Linnaeus_LiteAppDelegate *appDelegate = (Linnaeus_LiteAppDelegate*) [UIApplicat
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_访问错误,这表明它可能与内存有关,但我不明白为什么
NSLog(@"Data: %@", sqlite3_column_text(dbps_species, 1));
由于sqlite3\u column\u text
的结果是C字符串(char*
),而不是NSString*
,因此将导致EXC\u BAD\u访问
。要打印C字符串,您需要%s
格式说明符:
NSLog(@"Data: %s", sqlite3_column_text(dbps_species, 1));
另外,不要浪费时间调用
sqlite3\u column\u 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]];
}
您还可以尝试使用FMDB类。这使得使用sqlite变得更加容易
谢谢您的回复:)这就解释了为什么我当时无法调试它!我认为%@可以允许任何内容类型:(现在我已经能够进行调试,以表明我能够解决问题-谢谢!:D