existsman
existsman

Reputation: 39

how to store data from vb.net to access a database

I am using an Access database and vb.net 2010. I have created a table in the database with columns for title, datein, dateout and roomnymber. In vb.net 2010 I made a distinguished title = combobox, datein and dateout = DateTimePicker. When I click on F5, an error occurs: INSERT INTO Syntax Error in statement. Here's my code:

Dim sql As String
  sql = "INSERT INTO tcekin(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" & "VALUES('" & ComboBox1.Text & _
  "','" & txtFirstName.Text & "','" & txtLastName.Text & "','" & txtAddress.Text & "','" & cboCountry.Text & "','" & txtCompany.Text & "','" & txtNumber.Text & _
  "','" & dptDateIn.Text & "','" & dptDateOut.Text & "','" & cboRoom.Text & "','" & txtNotes.Text & "')"
  cmmd = New OleDbCommand(sql, cnn)

Upvotes: 0

Views: 2584

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

The first problem here is never NEVER NEVER use string concatenation to build your queries like that. Do it like this instead:

Dim sql As String = _
    "INSERT INTO tcekin " &_
    "(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" &_
    "VALUES(?,?,?,?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.Parameters.AddWithValue("Title", Combobox1.Text)
cmmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
''# ...
''# ...

This will also make it easier to spot and avoid syntax errors like the one you're complaining about.

Upvotes: 3

Related Questions