2013-07-22 74 views
0

我有一个DBManager这是从数据库中提取数据(sqlite文件)。所有其他查询都很好,但是这一次似乎有点不工作Sqlite数据库不能读取列

-(NSArray *)readCountries{ 
NSLog(@"[DBManager] readCountries"); 
NSMutableArray *countriesArray = [[NSMutableArray alloc] init]; 
//open db from users filesystem 
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { 
    const char* sql = "SELECT DISTINCT country FROM aed ORDER BY rowid"; 
    sqlite3_stmt *statement; 
    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) { 
     //loop through results 
     while (sqlite3_step(statement) == SQLITE_ROW) { 
      //read data from record 
      NSString *_country; 
      char* tmpCountry = (char*)sqlite3_column_text(statement, 1); 
      NSLog(@"tmpCountry = %@", [NSString stringWithUTF8String:tmpCountry]); 
      if (tmpCountry != NULL) { 
       _country = [NSString stringWithUTF8String:tmpCountry]; 
      }else{ 
       _country = @"n/a"; 
      } 
      NSLog(@"country = %@", _country); 
      [countriesArray addObject:_country]; 
     } 
    } 
    //finalize statement 
    sqlite3_finalize(statement); 
} 
//close database 
sqlite3_close(database); 
NSLog(@"[DBManager] countriesArray has %d objects", [countriesArray count]); 
return (NSArray*)countriesArray; 

}

所有我从日志中获取的,我的数组有5个对象,这是很好的 - 但它souldn't是只有“不适用”...任何想法?其他查询是好的,他们大多使用sqlite3_column_text,所以我不明白,为什么它不在这里工作 - 也许一个新的眼睛会有所帮助。

+0

rmaddy关于日志的说法 - 就像你写的代码会默默地失败,而不是让你知道什么是错的。 (并且sqlite3_errmsg通常是相当丰富的。) –

回答

1

这是一个与sqlite C-api混淆不一致。当使用sqlite3_column_xxx函数时,列索引是从0开始的。但是对于sqlite3_bind_xxx函数,列索引是基于1的。

更改此:

char* tmpCountry = (char*)sqlite3_column_text(statement, 1); 

到:

char* tmpCountry = (char*)sqlite3_column_text(statement, 0); 

顺便说一句 - 你应该添加else语句您sqlite3_opensqlite3_prepare电话。如果失败,可以使用sqlite3_errmsg函数记录错误。

+0

也应该检查sqlite3_step的返回代码,但它需要更多的工作,因为在假定错误之前必须过滤掉SQLITE_DONE。 –

+0

谢谢你,虽然我确实有0,但它现在不工作 - 看起来xcode也需要一些睡眠时间;) – raistlin