2016-09-14 57 views
0

我試圖設置一個按鈕,將保存給定的字段到SQLite數據庫。我能夠創建表,但單擊按鈕上的插入語句給我一個SQLite_MISUSE錯誤,而不是給我SQLite_OK。我無法弄清楚我的代碼中存在什麼問題,請讓我知道你是否有任何線索知道爲什麼會發生這種情況。獲取SQLite濫用錯誤

- (IBAction)SignUp:(id)sender { 
    sqlite3_stmt *statement; 
    const char *dbPath = [_databasePath UTF8String]; 

    if(sqlite3_open(dbPath, &_DB) == SQLITE_OK) { 
     NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO users(username, email, password) values(\"%@\", \"%@\", \"%@\")", _Username.text, _Email.text, _Password1.text]; 

     const char *insert_statement = [insertSQL UTF8String]; 
     sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL); 


     if(sqlite3_step(statement) == SQLITE_DONE) { 
      //below creates a popup success message upon adding user to the db 
      UIAlertController * alert = [UIAlertController 
             alertControllerWithTitle:@"Congrats!" 
             message:@"You are now a member" 
             preferredStyle:UIAlertControllerStyleAlert]; 

      UIAlertAction* okButton = [UIAlertAction 
             actionWithTitle:@"Ok" 
             style:UIAlertActionStyleDefault 
             handler:^(UIAlertAction * action) { 
             // 
             }]; 

      [alert addAction:okButton]; 
      [self presentViewController:alert animated:YES completion:nil]; 

      //returns the text fields back to original empty state 
      _Username.text = @""; 
      _Email.text = @""; 
      _Password1.text = @""; 
      _Password2.text = @""; 
     } 
     else { 
      //some other error 
      UIAlertController * alert= [UIAlertController 
              alertControllerWithTitle:@"Some" 
              message:@"Other Error" 
              preferredStyle:UIAlertControllerStyleAlert]; 
      UIAlertAction* ok = [UIAlertAction 
           actionWithTitle:@"OK" 
           style:UIAlertActionStyleDefault 
           handler:^(UIAlertAction * action) 
           { 
            [alert dismissViewControllerAnimated:YES completion:nil]; 
           }]; 
      [alert addAction:ok]; 
      [self presentViewController:alert animated:YES completion:nil]; 
     } 
     sqlite3_close(_DB); 
    } 
} 

回答

1

您對發佈的代碼有幾個問題。

  1. 您從未完成準備好的語句。
  2. 您不需要對sqlite3_prepare_v2的呼叫進行任何錯誤檢查。
  3. 千萬不要用stringWithFormat:建立查詢。使用適當的sqlite3_bind_xxx函數將值正確綁定到查詢中。

有關解決這些問題的示例,請參閱https://stackoverflow.com/a/39001417/1226963

+0

太棒了,謝謝! – dgelinas21

+0

很高興我能幫到你。不要忘記投票和/或接受有用的答案。 – rmaddy