2012-02-03 47 views
0

我正在使用XCode 4.2創建iphone應用程序。我正在使用sqlite3數據庫的應用程序。當我在XCode 4.2上遇到問題時,我在iPhone 3GS和XCode 3.2.5上成功創建並運行了該應用程序。 db文件無法打開,這裏是打開表格的示例代碼。當我使用SQlite管理器打開同一個db文件時,我可以看到表格。我不明白錯誤是什麼。Sqlite3數據庫表無法在XCode 4.2中打開

static sqlite3 *database = nil; 
static sqlite3_stmt *selectStmt = nil; 

+ (void) getInitialDataToDisplay:(NSString *)dbPath { 
    NSLog(@"Path: %@",dbPath); 
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { 
     NSString *sqlStr = @"select * from Space"; 
     const char *sql = [sqlStr UTF8String]; 
     sqlite3_stmt *selectstmt; 
     if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) { 
      while(sqlite3_step(selectstmt) == SQLITE_ROW) { 
       NSInteger primaryKey = sqlite3_column_int(selectstmt, 0); 
       SpaceClass *spaceObj = [[SpaceClass alloc] initWithPrimaryKey:primaryKey]; 
       spaceObj.spacePK = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]; 
       spaceObj.spName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)]; 
       spaceObj.spDescrptn = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];    
       [appDelegate.spaceArray addObject:spaceObj]; 
       [spaceObj release]; 
      } 
     }else 
      NSLog(@"not ok"); 
    } 
    else 
     sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory. 
} 

請幫幫忙,謝謝

+0

你可以檢查'NSLog(@「Error =%s」,sqlite3_errmsg(&db))'給出了什麼? – iNoob 2012-02-03 12:13:58

回答

2

你把接近的方法錯了地方,我認爲。我一直在iOS中使用SQLite3 2周,我有這個問題。我通過將SQLite3_close方法放在if(open == ok)的最後一行來解決這個問題。

您的代碼應該是這樣的:

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) 
{  
    if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) 
    { 
     while(sqlite3_step(selectstmt) == SQLITE_ROW) 
     { 

     } 
    } 
    else 
    { 
     NSLog(@"not ok"); 
    } 
    //here you should close database, before exit from if open block 
    sqlite3_close(database); 
} 
else 
{ 
    //here is not needed because of database open failure 
    //sqlite3_close(database); 
    NSLog(@"not ok"); 
} 

因爲現在你要每次打開它時關閉數據庫,這應該解決您的問題。但是在你的代碼中,你一次又一次地打開它而不關閉它!