2013-08-16 22 views
0

我正在使用以下代碼將一行插入到數據庫中。出於某種原因,sqlite3_last_insert_rowid爲插入的第一行返回正確的行ID,但在此之後它始終返回0.sqlite3_last_insert_rowid在第一次插入後返回0

在插入其他數據庫操作之間可能發生過類似刪除行的操作。

_scoresDB是一個實例var。

這裏是我的插入代碼:

-(void)insertScore:(OKScore*)score 
{ 
    const char *dbpath = [[self dbPath] UTF8String]; 

    if(sqlite3_open(dbpath, &_scoresDB) == SQLITE_OK) { 

     // Setup the SQL Statement 
     if(insertScoreStatement == nil) { 
      //OKLog(@"Preparing statement for cache score"); 
      const char *insertSQL = "INSERT INTO OKCACHE(leaderboardID,scoreValue,metadata,displayString,submitted) VALUES(?,?,?,?,?);"; 

      if(sqlite3_prepare_v2(_scoresDB, insertSQL, -1, &insertScoreStatement, NULL) != SQLITE_OK) { 
       OKLog(@"Failed to prepare score insert statement with message: '%s'", sqlite3_errmsg(_scoresDB)); 
       return; 
      } 
     } 

     // Bind the score values to the statement 
     sqlite3_bind_int(insertScoreStatement, 1, [score OKLeaderboardID]); 
     sqlite3_bind_int64(insertScoreStatement, 2, [score scoreValue]); 
     sqlite3_bind_int(insertScoreStatement, 3, [score metadata]); 

     if([score displayString]) { 
      sqlite3_bind_text(insertScoreStatement, 4, [[score displayString] UTF8String], -1, SQLITE_TRANSIENT); 
     } else { 
      sqlite3_bind_null(insertScoreStatement, 4); 
     } 
     sqlite3_bind_int(insertScoreStatement, 5, (int)[score submitted]); 

     //Execute the SQL statement 
     if(sqlite3_step(insertScoreStatement) == SQLITE_DONE) { 
      int scoreID = sqlite3_last_insert_rowid(_scoresDB); 
      [score setOKScoreID:scoreID]; 
      OKLog(@"Cached score : %@",score); 
     } else { 
      OKLog(@"Failed to store score in cache wihth error message: %s",sqlite3_errmsg(_scoresDB)); 
     } 


     sqlite3_reset(insertScoreStatement); 
     sqlite3_clear_bindings(insertScoreStatement); 
     sqlite3_close(_scoresDB); 

    } else { 
     OKLog(@"Could not open cache DB insertScore"); 
    } 
} 

回答

1

你不能讓一個聲明爲一個已經關閉的數據庫。 如果您嘗試重新使用舊語句,則不會插入任何內容(既不會插入舊數據庫,因爲它已關閉,也不會插入新數據庫,因爲語句不知道它)。

在關閉數據庫之前,您需要必須免費聲明與sqlite3_finalize

1

我不認爲你應該保留您insertScoreStatement。你已經爲它綁定了價值,現在你正在綁定更多的東西。我想使它成爲一個局部變量(不是一類一也不是一個屬性)是這樣的:

// Setup the SQL Statement 
    sqlite3_stmt *insertScoreStatement 
    //OKLog(@"Preparing statement for cache score"); 
    const char *insertSQL = "INSERT INTO OKCACHE(leaderboardID,scoreValue,metadata,displayString,submitted) VALUES(?,?,?,?,?);"; 

    if(sqlite3_prepare_v2(_scoresDB, insertSQL, -1, &insertScoreStatement, NULL) != SQLITE_OK) { 
     OKLog(@"Failed to prepare score insert statement with message: '%s'", sqlite3_errmsg(_scoresDB)); 
      return; 
     } 
    } 
相關問題