Sam Lev Sam Lev - 1 day ago 4
Vb.net 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;")
Try
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
cmd.Connection = con
con.Open()
MsgBox("Connection Open ! ")
cmd.ExecuteNonQuery()
MsgBox("Record inserted")
con.Close()
Catch ex As Exception
MsgBox("Error!")
End Try
End Sub

Answer

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

Comments