Access 2010的INSERT INTO语句中的语法错误

时间:2013-10-28 05:18:37

标签: vb.net ms-access-2010

我的INSERT语句显然有语法错误。有人可以解释为什么会这样吗?

Private Sub Register_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Register.Click
    Dim StudentNum As String
    Dim Password As String
    Dim FirstName As String
    Dim LastName As String
    Dim YrandSec As String

    StudentNum = Number.Text()
    Password = Pass.Text
    FirstName = First.Text
    LastName = Last.Text
    YrandSec = YrSec.Text()

    SQL = "INSERT INTO Accounts(StudNo,Password,FirstName,LastName,YrandSec) VALUES ('" & StudentNum & "', '" & Password & "', '" & FirstName & "', '" & LastName & "', '" & YrandSec & "')"    - ERROR HERE
    Cmd = New OleDbCommand(SQL, Con)
    Con.Open()
    objCmd = New OleDbCommand(SQL, Con)

    If Repass.Text = Pass.Text = False Then
        Re.Text = "*Password didn't match!"
        Number.Text = ""
        Pass.Text = ""
        Repass.Text = ""
        Con.Close()
    Else
        If Number.Text = "" Or Pass.Text = "" Or Repass.Text = "" Or First.Text = "" Or Last.Text = "" Or YrSec.Text = "" Then
            MsgBox("Please complete the field", MsgBoxStyle.Information, "Failed to create")
        Else
            objCmd.ExecuteNonQuery()
            Re.Text = ""
            MsgBox("Account has been created", MsgBoxStyle.Information, "Congrats!")
            For fade = 0.0 To 1.1 Step 0.2
                Login.Opacity = fade
                Login.Show()
                Me.Hide()
                Threading.Thread.Sleep(30)
                Number.Text = ""
                Pass.Text = ""
                Repass.Text = ""
                First.Text = ""
                Last.Text = ""
                YrSec.Text = ""
            Next
        End If

    End If
End Sub

2 个答案:

答案 0 :(得分:7)

  1. PASSWORD是Access SQL中的reserved word,因此您需要将该列名称包装在方括号中。

  2. 您确实应该使用参数化查询来防范 SQL Injection ,并且通常会让您的生活更轻松。

  3. 尝试这样的事情

    SQL = "INSERT INTO [Accounts] ([StudNo],[Password],[FirstName],[LastName],[YrandSec]) " & _
            "VALUES (?, ?, ?, ?, ?)"
    Con.Open()
    objCmd = New OleDbCommand(SQL, Con)
    objCmd.Parameters.AddWithValue("?", StudentNum)
    objCmd.Parameters.AddWithValue("?", Password)
    objCmd.Parameters.AddWithValue("?", FirstName)
    objCmd.Parameters.AddWithValue("?", LastName)
    objCmd.Parameters.AddWithValue("?", YrandSec)
    

答案 1 :(得分:0)

删除sql语句中的双引号。