2

我正在尝试使用 SQL 命令将新记录插入数据库,但每次运行程序并尝试添加新记录时,我都会收到一个错误消息,告诉我“INSERT INTO”语句存在语法错误。我插入的数据存储在数组 + 结构中:

    Structure Question
        Dim QuestionName As String
        Dim Question As String
        Dim Ans1 As String
        Dim Ans2 As String
        Dim Ans3 As String
        Dim Ans4 As String
        Dim Difficulty As Integer
        Dim CorrectAns As String
    End Structure

    Dim arrQuestion as Question

这是用于将记录插入数据库的子 im:

    Try

        Dim InsertComm As New OleDb.OleDbCommand
        Dim dbAdap As New OleDb.OleDbDataAdapter

        ConnectToDB()

        Dim sqlInsert As String = "INSERT INTO questionDatabase(QuestionName, Question, 
                                   Answer 1, Answer 2, Answer 3, Answer 4, Correct answer,
                                   Difficulty ID) VALUES(" & Chr(39) & arrquestion.questionname 
                                   & Chr(39) & ", " & Chr(39) & arrquestion.question & Chr(39) &
                                   ", " & Chr(39) & arrquestion.ans1 & Chr(39) & ", " & Chr(39) 
                                   & arrquestion.ans2 & Chr(39) & ", " & Chr(39) & 
                                   arrquestion.ans3 & Chr(39) & ", " & Chr(39) & 
                                   arrquestion.ans4 & Chr(39) & ", " & Chr(39) & 
                                   arrquestion.correctans & Chr(39) & ", " & Chr(39) & 
                                   arrquestion.difficulty & Chr(39) & ");"

        InsertComm = New OleDb.OleDbCommand(sqlInsert, dbConn)

        InsertComm.ExecuteNonQuery()

        dbConn.Close()

    Catch ex As Exception
        MsgBox(Err.Description)
    Finally
        dbConn.Close()
    End Try

我已经写了又改了很多次,用谷歌搜索它给我的错误,并试图复制人们在那里发布的解决方案,但我就是无法理解他们是如何编写代码的。任何帮助将不胜感激。

4

1 回答 1

4

你的语句的核心应该这样写

Dim sqlInsert As String = "INSERT INTO questionDatabase(QuestionName, Question, " +
      "[Answer 1], [Answer 2], [Answer 3], [Answer 4], [Correct answer], " +
      "[Difficulty ID]) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"
InsertComm = New OleDb.OleDbCommand(sqlInsert, dbConn)
InsertComm.Parameters.AddWithValue("@p1", arrquestion.questionname)
InsertComm.Parameters.AddWithValue("@p2", arrquestion.question )
InsertComm.Parameters.AddWithValue("@p3", arrquestion.ans1)
InsertComm.Parameters.AddWithValue("@p4", arrquestion.ans2)
InsertComm.Parameters.AddWithValue("@p5", arrquestion.ans3)
InsertComm.Parameters.AddWithValue("@p6", arrquestion.ans4)
InsertComm.Parameters.AddWithValue("@p7", arrquestion.correctans)
InsertComm.Parameters.AddWithValue("@p8", arrquestion.difficulty)
InsertComm.ExecuteNonQuery()

可以看到,首先是用方括号将每个字段名封装起来,解决字段名中的空格问题。第二点是使用参数化查询来避免解析问题(字符串中的引号、日期、小数等)和最重要的Sql Injection

另请注意,OleDb 环境中的参数应按照它们各自的占位符 (?) 在 sql 文本中出现的顺序添加到 ParametersCollection

于 2013-01-29T20:16:29.363 回答