2016-09-14 47 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