2011-06-14 37 views
0

我需要幫助使用Objective C和iPhone SDK將新條目寫入SQLite數據庫。寫入SQLite數據庫目標C Iphone SDK

打開/關閉/讀取數據庫操作還行,但我無法弄清楚爲什麼這段代碼不起作用。

-(void) testWriteToDatabase{ 

NSLog(@"instructions sent 3"); 
    sqlite3 *database; 
    sqlite3_stmt *compiledStatement; 
const char *insertSql="INSERT INTO data (name,pass,email) VALUES(?,?,?)"; 

NSString *userRegistered=userRegister.text; 
NSLog(@"user %@",userRegistered); 
NSString *passRegistered=passRegister.text; 
NSLog(@"pass %@",passRegistered); 
NSString *emailRegistered=emailRegister.text; 
NSLog(@"email %@",emailRegistered); 
sqlite3_stmt *insertStmt = nil; 



if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_OK) { 

    if(sqlite3_prepare_v2(database, insertSql, -1, &insertStmt, NULL) == SQLITE_OK){ 

NSLog(@"instructions sent 4"); 
sqlite3_bind_text(insertStmt, 1, [userRegistered UTF8String], -1, SQLITE_TRANSIENT); 
sqlite3_bind_text(insertStmt, 2, [passRegistered UTF8String], -1, SQLITE_TRANSIENT); 
sqlite3_bind_text(insertStmt, 3, [emailRegistered UTF8String], -1, SQLITE_TRANSIENT); 
      NSLog(@"instructions sent 5"); 
     while (sqlite3_step(compiledStatement) == SQLITE_ROW) { 


     } 

    } 
sqlite3_reset(insertStmt);  
    } 
sqlite3_close(database);  
} 

誠實的,我從來沒有真正使用過SQLite的,但主要的問題是它沒有將條目添加到數據庫「數據」像我想它。幫助將不勝感激,歡呼聲。

+0

你直接與sqlite交談並且不打擾核心數據的任何原因? – Thom 2011-06-14 19:39:02

+1

我強烈建議圍繞SQLite使用Gus Mueller的FMDatabase包裝類。 https://github.com/ccgus/fmdb – 2011-06-14 19:40:36

+0

我希望能夠下載/上傳數據庫到服務器,所以它不是限制性的。說實話,我從來沒有真正考慮過它:/ – gunmania0 2011-06-14 19:41:59

回答

3

不應該

while (sqlite3_step(compiledStatement) == SQLITE_ROW) { 
} 

while (sqlite3_step(insertStmt) == SQLITE_ROW) { 
} 

爲你使用insertStmt其他任何地方。 compiledStatement未定義,因爲我瞭解您的代碼。

+0

完美,非常感謝您的親切先生。 – gunmania0 2011-06-14 21:31:36

0

數據庫是否有一個名爲「數據」的表?平凡的事情,但仍然。另外,請檢查sqlite3_step每一步都返回什麼。

+0

是的,它確實有一個名爲數據的表,好吧,我會檢查。 – gunmania0 2011-06-14 19:50:55

+0

我努力尋找調用Sqlite3_step函數返回的代碼... - 正如我所說我是一個完全新手與SQLite:/ – gunmania0 2011-06-14 19:59:10

+0

我跑這條命令:'NSLog(@「Insert into row id =% d「,sqlite3_last_insert_rowid(database));'它返回的答案是0. – gunmania0 2011-06-14 20:05:41