Syntax error in insert statement

I am new to connecting to the database, and when I had a problem with the string cmdInsert.ExecuteNonQuery(), it talks about a syntax error with the INSERT INTO statement, and I cannot figure out what the problem is:

Imports System.Data
Imports System.Data.OleDb
Public Class txtNotes
    Dim cnnOLEDB As New OleDbConnection
    Dim cmdInsert As New OleDbCommand

    Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\CourseworkDB"
    'the name of the database goes in here'

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        cnnOLEDB.ConnectionString = strConnectionString
        cnnOLEDB.Open()

    End Sub

    Private Sub AddFirstName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFirstName.Click
        If txtFirstName.Text <> "" Then

            MsgBox(cmdInsert.CommandText)
            cmdInsert.CommandText = "INSERT INTO Customer (First Name) VALUES (" & txtFirstName.Text & ", '"
            cmdInsert.CommandType = CommandType.Text
            cmdInsert.Connection = cnnOLEDB
            cmdInsert.ExecuteNonQuery()
        Else
            MsgBox("Enter the required values:" & vbNewLine & "1. First Name")
        End If
        cmdInsert.Dispose()
    End Sub
End Class
0
source share
3 answers

I highly recommend not getting into the routine of building SQL strings by concatenating strings. You leave yourself wide open for SQL injection, especially if it is a website. You must create your commands with place-holder parameters in the line, and then add the parameters to the command object. Add the parameters in the same sequence as in the command ... for example

cmdInsert.CommandText = "INSERT INTO Customer (FirstName, LastName) VALUES ( @parmFirstName, @parmLastName )"
cmdInsert.Parameters.AddWithValue( "@parmFirstName", txtFirstName.Text );
cmdInsert.Parameters.AddWithValue( "@parmLastName", txtLastName.Text );

, -, ( 1) . "". , [].

+1

"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"

0

: Bobby .

cmdInsert.CommandText = _
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"
0

All Articles