SYNTAX错误插入声明Visual Basic

时间:2015-08-23 07:08:48

标签: vb.net

为什么我收到此错误

  

语法错误INSERT INTO语句

请帮忙!提前谢谢!

Dim cmd As New OleDb.OleDbCommand
    If TabControl1.SelectedIndex = 0 Then

        If Not cnn.State = ConnectionState.Open Then
            'open connection if it is not yet open
            cnn.Open()
        End If

        cmd.Connection = cnn
        'check whether add new or update
        If Me.txtStdID.Tag & "" = "" Then
            'add new 
            'add data to table
            cmd.CommandText = "INSERT INTO Student (StudentID, LastName, FirstName, MiddleInitial, Grade, Section, ContactNumber, AdviserID, CounselorID, ParentName)" & _
                            "VALUES('" & Me.txtStdID.Text & "','" & Me.txtLname.Text & "','" & _
                            Me.txtFname.Text & "','" & Me.txtMidInt.Text & "','" & _
                            Me.txtGrade.Text & "','" & Me.txtSection.Text & "','" & Me.txtContact.Text & "','" & _
                            Me.txtAdvID.Text & "','" & Me.txtConID.Text & "','" & Me.txtPname.Text & "')"
            cmd.ExecuteNonQuery()

1 个答案:

答案 0 :(得分:2)

嗯,这是一个众所周知的问题。数据库将许多单词定义为“保留关键字”,如果它们用于列名或表名,则需要将它们括在数据库的相应引号字符中。

看到您正在使用OleDbConnection我假设您使用MS-Access作为数据库。在这种情况下,list of reserved keywords could be found here

事实上,SECTION是一个保留关键字,所以你的查询应该写成

"INSERT INTO Student (......, [Section], ......

说,让我们说一下字符串连接来构建SQL查询。

这是坏事,坏事,坏事...... 这有很多问题。例如,如果您的某个字段包含单引号会发生什么?整个查询将再次失败,并出现语法错误。此外,虽然更难以利用Access,因为它不支持多个命令文本,但SQL Injection存在不惜一切代价避免的问题。您需要了解如何使用PARAMETERIZED QUERY

Dim sqlText = "INSERT INTO Student (StudentID, LastName, FirstName, " & _ 
              "MiddleInitial, Grade, [Section], ContactNumber, AdviserID, " & _ 
              "CounselorID, ParentName) VALUES (?,?,?,?,?,?,?,?,?,?)"
If TabControl1.SelectedIndex = 0 Then
    Using cnn = New OleDbConnection(...constring here....)
    Using cmd = new OleDbCommand(sqlText, cnn)
       cnn.Open()
       cmd.Parameters.Add("@p1", OleDbType.VarWChar).Value = Me.txtStdID.Text
       cmd.Parameters.Add("@p2", OleDbType.VarWChar).Value = Me.txtLname.Text
       .... and so on with the other parameters ....
       .... strictly following the order of the fields in the insert....
       cmd.ExecuteNonQuery()
  End Using
  End Using