Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm a new coder, working with inserting a first and last name into a DB table. I thought I had this pretty well thought out, however I'm getting the following error.

C#
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Incorrect syntax near 'Cooper'.


Here is my Code block handling the INSERT statement.

VB.NET
    If (myConn.State = ConnectionState.Closed) Then myConn.Open()
    Dim myNewEntry As New SqlCommand(("INSERT INTO SCOUTINFO (FIRSTNAME, LASTNAME)
                           values('" & txtFirstName.Text & "'), ('" & txtLastName.Text & "'"), myConn)
    myNewEntry.ExecuteNonQuery()
End If


What I have tried:

I've tried different formats of the INSERT, and tried to understand if there's some better method to do an insert. I've seen DATASET stuff, but don't understand it, and since Im new, I'm trying what seems the most direct path.
Posted
Updated 22-Jun-16 18:37pm
Comments
Depotdad80 22-Jun-16 21:14pm    
By the way, the error is occurring at the LASTNAME portion. I removed it, just trying the FIRSTNAME, but got the same error. So Im not quite sre what is breaking the statement.

Your error is here:
VB
Dim myNewEntry As New SqlCommand(("INSERT INTO SCOUTINFO (FIRSTNAME, LASTNAME)
                           values('" & txtFirstName.Text & "'), ('" & txtLastName.Text & "'"), myConn)


My fix:
VB
Dim myNewEntry As New SqlCommand(("INSERT INTO SCOUTINFO (FIRSTNAME, LASTNAME)
                           values('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"), myConn)
 
Share this answer
 
v2
Comments
Depotdad80 23-Jun-16 9:22am    
Thank you!
the syntax error and the fix is availble in solution1 by casper

but you code is vulnerable to SQL Injection[^] attacks.

always use Parameterized queries to prevent SQL Injection Attacks [^]

VB.NET
Dim myNewEntry As New SqlCommand("INSERT INTO SCOUTINFO (FIRSTNAME, LASTNAME) values(@first,@last)")
     myNewEntry.Parameters.Add("@first", txtFirstName.Text)
     myNewEntry.Parameters.Add("@first", txtLastName.Text)
     myNewEntry.ExecuteNonQuery()
 
Share this answer
 
Comments
Depotdad80 23-Jun-16 9:23am    
Thank you very much! I just had a programmer in my office point out that exact thing this morning. Looks like I have much more reading to do, so that I understand the Parameters command.
Karthik_Mahalingam 23-Jun-16 9:25am    
cool,
if your issue is resolved, please close this post by marking it as answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900