2013-11-09 108 views
0

我正在使用SQLite3在我的iPhone應用程序中做登錄表單。用戶名和密碼已成功上傳到數據庫,但是當我檢查數據的存在時,我得到一個錯誤。這是我使用的代碼時,試圖趕上數據:檢查數據庫中是否存在用戶名 - SQLite3&objective-c

- (IBAction)loginTapped:(id)sender 
{ 
if (sqlite3_open([self.filePath UTF8String], &db) == SQLITE_OK) 
{ 
    NSString *sql = [NSString stringWithFormat:@"SELECT username, password FROM register WHERE username = '%@'",[self.usernameLogin text]]; 
    sqlite3_stmt *statement; 
    if (sqlite3_prepare_v2(db, sql.UTF8String, -1, &statement, NULL) == SQLITE_OK) 
    { 
     if (sqlite3_step(statement) == SQLITE_ROW) 
     { 
      char *f1 = (char *)sqlite3_column_text(statement, 1); 
      NSString *user = [[NSString alloc] initWithUTF8String:f1]; 
      char *f2 = (char *)sqlite3_column_text(statement, 2); 
      NSString *pass = [[NSString alloc] initWithUTF8String:f2]; 
      NSLog(@"User : %@, Password : %@",user, pass); 
     } 
    } 

    sqlite3_finalize(statement); 
} 
sqlite3_close(db); 
} 

當這個方法被調用我得到這個錯誤:

2013-11-09 22:34:24.702 SQLiteTest[1385:60b] *** Terminating app due to uncaught exception  'NSInvalidArgumentException', reason: '*** -[NSPlaceholderString initWithUTF8String:]: NULL cString' 
*** First throw call stack: 
(0x2f5eef53 0x399c76af 0x2f5eee95 0x2ff24f87 0xf7789 0x31d94f3f 0x31d94edf 0x31d94eb9 0x31d80b3f 0x31d9492f 0x31d94601 0x31d8f68d 0x31d64a25 0x31d63221 0x2f5ba18b 0x2f5b965b 0x2f5b7e4f 0x2f522ce7 0x2f522acb 0x34243283 0x31dc4a41 0xf7d25 0x39ecfab7) 
libc++abi.dylib: terminating with uncaught exception of type NSException 
(lldb) 

什麼可能是錯誤的?

回答

0

列索引從零開始:

 char *f1 = (char *)sqlite3_column_text(statement, 0); 
     char *f2 = (char *)sqlite3_column_text(statement, 1); 
+0

不應該是問題,在索引0我有另一列... –

+0

這些都是*語句*的列索引,而不是*表*。該查詢返回恰好兩列。 –

0

添加檢查該值從數據庫來不是創建一個字符串出來之前空。像:

NSString *user; 
NSString *pass; 

char *f1 = (char *)sqlite3_column_text(statement, 1); 
if(f1 != NULL) 
    user = [[NSString alloc] initWithUTF8String:f1]; 

char *f2 = (char *)sqlite3_column_text(statement, 2); 
if(f2!= NULL) 
    pass = [[NSString alloc] initWithUTF8String:f2]; 

NSLog(@"User : %@, Password : %@",user, pass); 
+0

如果我輸入一個用戶名,或者只是輸入任何內容,那麼'if(sqlite3_step(statement)== SQLITE_OK){}'根本不會被執行。但是,如果我將'usernameLogin'保留爲空,那麼if-statement被執行,然後我發現'f1'和'f2'不是空,並且記錄了消息,但是沒有佔位符的文本 –

相關問題