2012-11-09 526 views
0

我花了幾天的時間試圖解決這個問題,我放棄了! 我正在做的是從用戶接收輸入,並將其插入數據庫,如果他按下「保存」按鈕。 當我運行這個代碼,並按下「保存」按鈕後。 1-不能退出視圖(到另一個選項卡)。 2-插入沒有應用!在數據庫中插入SQlite錯誤

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"]; 
    sqlite3 *database; 


    //Copy the database from the package to the usrrs filesystem 
    if (sqlite3_open([dbPath UTF8String], &database)== SQLITE_OK) {//start if 
     NSLog(@"dataBaseOpen"); 
     const char *sqlStatement = "insert into Location (Latitude,Longitude,LocationName,Tag) VALUES (?,?,?,?)"; 
     // 
     sqlite3_stmt *compileStatement; 

     if (sqlite3_prepare_v2(database, sqlStatement, -1, &compileStatement, NULL) == SQLITE_OK) { // start if 2 
      if(SQLITE_DONE!=sqlite3_step(compileStatement)) 
      { 
      sqlite3_bind_double(compileStatement, 1, [latitudeTextField.text doubleValue]); 

      sqlite3_bind_double(compileStatement, 2, [longitudeTextField.text doubleValue]); 

      sqlite3_bind_text(compileStatement, 3, [lName.text UTF8String], -1, SQLITE_TRANSIENT); 

      sqlite3_bind_text(compileStatement, 4, [myText.text UTF8String] ,-1, SQLITE_TRANSIENT); 
      NSLog(@" successfully done"); 
      if(sqlite3_step(compileStatement) != SQLITE_DONE) { 
       NSLog(@" not done"); 
      } 
      } 

     } 
    } 

和我把的appDelegate代碼在文件管理器應對:

的NSArray *路徑= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString * documentsDir = [paths objectAtIndex:0];

NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"]; 


NSFileManager *fileManager = [NSFileManager defaultManager]; 

BOOL success = [fileManager fileExistsAtPath:dbPath]; 

if (success) { 

    NSLog(@"we have the database"); 

} else { 

    NSLog(@"we have no database"); 

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"]; 


    BOOL moved = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:nil]; 

    if (moved) { 
     NSLog(@"database copied"); 
    } 



} 

我錯過了什麼!問題是什麼 !!

回答

0

對於你#2的問題: 1.你有一個額外的sqlite_step調用。您的順序應該是:

sqlite3_prepare_v2() 
      sqlite_bind_.... 
      sqlite_bind_.... 
      for as many bind's as you need, and then 
      sqlite_step() 
  1. 如果sqlite_step仍然失敗,檢查返回代碼,並尋求指導在文檔

  2. 如果您的MacOS應用是Sandbox'd,這不會工作。目前沒有辦法自行更新sqlite數據庫。您必須獲得用戶對sqlite文件所在目錄的寫入權限,或者必須將其放入包中(實際上是相同的東西)

+0

謝謝morejanus !!!!它運作良好 – Alaa12

+0

但NSLog打印「成功完成」,但我怎麼能打開數據庫,並檢查行是否存在! 當我通過SQlite插件打開它時,我沒有找到它!這是否意味着它是錯誤的? – Alaa12