Sam Lev Sam Lev - 8 months ago 37 Question

What's wrong with this SQL Insert statement of mine?

I am trying to add a record to my table, however I'm getting an exception after it attempts to do so. I am able to open the connection successfully, (my first messagebox shows up) but after that I get the exception. Here's my code:

Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;")
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
cmd.Connection = con
MsgBox("Connection Open ! ")
MsgBox("Record inserted")
Catch ex As Exception
End Try
End Sub

Answer Source

You need to look at the exception message (ex.Message) see what the issue is...If you have an error similar to multipart identifier then try this query string instead of your current query string for a quick test.

    cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES ('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"

Check out parameterized query as previously indicated