2012-12-27 17 views
0

這裏我優化下面的代碼我得到完美的數據庫路徑意味着NSLog(@「在保存數據::%s」,dbasePath);但在那之後不能如果條件碼它不能在插入數據庫工作

-(void)saveData{ 
    sqlite3_stmt *statment; 
    dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    docsDir=[dirPath objectAtIndex:0]; 
    const char *dbasePath=[dbPath UTF8String]; 
    NSLog(@"in save data::%s",dbasePath); 

    if (sqlite3_open(dbasePath, &sqlDatabase)) { 
     NSString *insert_query=[NSString stringWithFormat:@"INSERT INTO PRJDATA VALUES(\"%@\",\"%@\"\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",title,timeGet1.text,timeGet2.text,timeGet3.text,dateField.text,interval1.text,interval2.text]; 
     NSLog(@"query string::%@",insert_query); 
     const char *insert_stmt=[insert_query UTF8String]; 
     NSLog(@"error in insert::%s",sqlite3_errmsg(sqlDatabase)); 
     sqlite3_prepare_v2(sqlDatabase, insert_stmt, -1, &statment, NULL); 
     if (sqlite3_step(statment)==SQLITE_DONE) { 
      [email protected]"content added"; 
      [email protected]""; 
      [email protected]""; 
      [email protected]""; 
      [email protected]""; 
      [email protected]""; 
      [email protected]""; 

     } 
     else{ 
      [email protected]"failed to add"; 
     } 
     sqlite3_finalize(statment); 
     sqlite3_close(sqlDatabase); 

    } 
} 

回答

1

一對夫婦的想法進行優化:

  1. 爲什麼設置,如果你的dbasePath不使用它們dirPathdocsDir?這是使用,你大概是想根據docsDir來定義,但是你在這裏沒有定義任何地方。

  2. 另外,你能告訴我們你的代碼示例中的NSLog結果嗎?相應地更新你的問題。在做NSLog沒有意義,但沒有與我們分享。

  3. 正如我在其他答案中所建議的那樣,無論何時出現錯誤,請顯示sqlite3_errmsg,因爲這會告訴您出了什麼問題。爲什麼猜猜你什麼時候可以讓SQLite告訴你什麼是錯的?如果你不顯示sqlite3_errmsg結果,你會自己動手。

  4. 您的VALUES在您的INSERT聲明中是否反映了表中的所有列?如果不是,則應該更改INSERT聲明以包含與您的值相對應的列的名稱,例如,

    INSERT INTO TABLE1 (COL1, COL2, COL3) VALUES ("VALUE1", "VALUE2", "VALUE3"); 
    
  5. 你真的不應該使用stringWithFormat來構建INSERT字符串。您應該使用?佔位符,然後使用sqlite3_bind_函數。有關sqlite3_bind函數的示例,請參閱Sqlite database locked when executing "END"(忽略問題,但只查看代碼示例中的sqlite3_bind語句)。這樣可以避免你不必處理奇怪的異常,比如title字段中有雙引號......這會破壞你當前的例程。它還可以防止SQL注入攻擊。這只是謹慎。