Can't insert values to my MS Access database using vb.net commands

40 Views Asked by At

I have been trying to insert a text value to a field in my MS Access Database but it shows Syntax Error in INSERT INTO.

      con.Open()
        Dim test As String
        test = cbHotCake.Text

        Dim addBF1 As New OleDbCommand("INSERT INTO TemporaryHolder (Order) VALUES ('" & test & "')", con)
        addBF1.ExecuteNonQuery()
        con.Close()

Here's the error message it shows:

Syntax error in INSERT INTO statement.

2

There are 2 best solutions below

0
Mary On

Connections and commands need to be disposed. Using...End Using blocks will do this for you even if there is an error. This will also close the connection. Pass the connection string to the constructor of the connection. Pass the command text and the connection to the constructor of the command.

Always use parameters. I had to guess at the datatype and field size, so check the database and correct the code.

Private Sub OPCode()
    Using con As New OleDbConnection("Your connection string"),
            addBF1 As New OleDbCommand("INSERT INTO TemporaryHolder (Order) VALUES (@test);", con)
        addBF1.Parameters.Add("@test", OleDbType.VarChar, 100).Value = cbHotCake.Text
        con.Open()
        addBF1.ExecuteNonQuery()
    End Using
End Sub
0
Gustav On

Most likely, you need to bracket the reserved word Order:

"INSERT INTO TemporaryHolder ([Order]) VALUES ('" & test & "')"