VB.net Syntax error in INSERT INTO statement (Alth

2020-02-13 07:12发布

问题:

I have tested this SQL statement in Microsoft Access and it work perfectly but for some reason it doesn't work in my code. I have checked it many times and I haven't figure out the syntax error (Although, it work in MS Access).

Here's the error message:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll

Additional information: Syntax error in INSERT INTO statement.

Here's my code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Now, when the Register button is clicked,
    'We check, if the user type is User, we create a normal User in the database.
    'Otherwise, we create a Wroker.

    Dim fname, lname, nationality, password As String
    Dim age, yearExpr, phone, saloonID, type As Integer

    fname = fNameBox.Text
    lname = LNameBox.Text
    age = Convert.ToInt32(ageBox.Text)
    phone = Convert.ToInt32(phoneBox.Text)
    password = passwordBox.Text


    If (userTypeCB.Text.Equals("User")) Then
        type = 1
        salSql = ""
        salCnc.Open()
        salSql = "INSERT INTO User ([Fname], [Lname], [Age], [Phone#], [Type], [Password])
                 VALUES (" & "'" & fname & "'" & "," & "'" & lname & "'" & "," & age & "," & phone & "," & type & "," & "'" & password & "'" & ")"


        salCommand = New OleDb.OleDbCommand(salSql, salCnc)
        salCommand.ExecuteNonQuery()

        salCnc.Close()



    ElseIf (userTypeCB.Text.Equals("Worker")) Then
        yearExpr = exprBox.Text
        saloonID = saloonBox.Text
        nationality = NationBox.Text

    End If
End Sub

Now, the compiler points to the salCommand.ExecuteNonQuery() as the error source. Any idea what's the problem?

回答1:

Credit to @LarsTech

User is a keyword. You have to put it in brackets. ie: INSERT INTO [User]...

Also, use a parameterized command to avoid SQL injection which could also be the cause of this syntax error.

'''code removed for brevity

salSql = "INSERT INTO [User] ([Fname],[Lname],[Age],[Phone#],[Type],[Password]) VALUES (?,?,?,?,?,?)"


salCommand = New OleDb.OleDbCommand(salSql, salCnc)

salCommand.Parameters.Add("@fname", fname)
salCommand.Parameters.Add("@lname", lname)
salCommand.Parameters.Add("@age", age)
salCommand.Parameters.Add("@phone", phone)
salCommand.Parameters.Add("@type", type)
salCommand.Parameters.Add("@password", password)

salCommand.ExecuteNonQuery()

'''code removed for brevity