oleDb Insert problem
-
I am getting errors when I try to insert data into my database. I dont have any problems viewing the database. I think it is a problem with my insert statement: oleDbInsertCommand1.CommandText="INSERT INTO UserTable(Username,Password) VALUES('@NewUserTextBox.Text','@NewPasswordTextBox.Text')"; oleDbInsertCommand1.ExecuteNonQuery(); I have even tried it without the @ and other ways. This is the error I get below. System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
-
I am getting errors when I try to insert data into my database. I dont have any problems viewing the database. I think it is a problem with my insert statement: oleDbInsertCommand1.CommandText="INSERT INTO UserTable(Username,Password) VALUES('@NewUserTextBox.Text','@NewPasswordTextBox.Text')"; oleDbInsertCommand1.ExecuteNonQuery(); I have even tried it without the @ and other ways. This is the error I get below. System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
You can do it this way, but it's susceptible to SQL injection attacks (a common way that malicious users can attack a web site and destroy databases): oleDbInsertCommand1.CommandText="INSERT INTO UserTable(Username,Password) VALUES('" + NewUserTextBox.Text + "','" + NewPasswordTextBox.Text + "')"; Instead you should set up an oleDbParameter collection and attach it to the oleDBInsertCommand1 object. You'd populate the paramters from the two textboxes (NewUserTextBox and NewPasswordTextBox). If you named these parameters '@NewUser' and '@NewPassword' respectively, then you'd code the CommandText as follows (notice that there are no single quotes here): oleDbInsertCommand1.CommandText="INSERT INTO UserTable(Username,Password) VALUES(@NewUser, @NewPassword)"; This is the secure, recommended best-practice solution. There is more help on parameter collections in the Visual Studio on-line help.