Thursday, March 22, 2012

Why the command executeNonQuery cannot be initialised?

I tried to insert some data into my database. Below is my code:

Try
If OleDbConnection1.State = ConnectionState.Closed Then
OleDbConnection1.Open()
End If

Me.OleDbSelectCommand1.CommandText = "INSERT INTO Table1 (First) Values ('" & TextBox1.Text & "')"
Me.OleDbSelectCommand1.Connection = Me.OleDbConnection1
Me.OleDbSelectCommand1.ExecuteNonQuery()
DataSet1.Tables("Table1").Rows.Clear()
OleDbDataAdapter1.Fill(DataSet1, "Table1")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Everything works fine, but when it came to Me.OleDbSelectCommand1.ExecuteNonQuery(), an error msg pop out saying Syntax error in INSERT INTO statement. Can anyone enlighten me? Thanks!
What is the value in TextBox1.Text? The error message is coming from your database.

In any case, you should always use parameters to build your SQL statements. Couple of benefits are:

1 - They take care of special characters based on the datatype of the column, so you don't have to worry about apostrophes, etc...
2 - They are great at preventing SQL injection attacks!

Have a look at the OleDbParamter class in the SDK documentation.

the data type in my database is Text and i typed in a word, sing, into my textbox. It then gives me the error.
Are you using MS Access? Try debugging your code, grab the SQL statement and paste it into Access Query. See what happens.

0 comments:

Post a Comment