我正在尝试使用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
我已经写过并重写了很多次,用谷歌搜索它给我的错误并尝试复制人们在那里发布的解决方案,但我无法理解他们如何编写代码。 任何帮助都会非常感激。
答案 0 :(得分: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中