我在insert into语句中遇到语法错误

时间:2013-08-19 14:56:06

标签: vb.net ms-access sql-insert

任何人都可以解决以下代码问题......

注意:前端vb8&后端访问7

Private Sub SaveData()
    Dim InsertString As String
    InsertString = "Insert into STUDENT DETAILS(SREGNO,SFIRSTNAME,SMIDDLENAME,SLASTNAME,SYEAR,SCOURSE,SSEM,SCLASS,SLANGUAGE)" & "Values('" & Me.TXTSREGNO.Text & "','" & Me.TXTSFIRSTNAME.Text & "','" & Me.TXTSMIDDLENAME.Text & "','" & Me.TXTSLASTNAME.Text & "','" & Me.COMB1SYEAR.Text & "','" & Me.COMB2SCOURSE.Text & "','" & Me.COMB3SSEM.Text & "','" & Me.COMB4SCLASS.Text & "','" & Me.COMB5SLANGUAGE.Text & " ');"
    Dim InsertCommand As New OleDbCommand(InsertString, Con)
    InsertCommand.ExecuteNonQuery()
    MsgBox("New record added successfully.", MsgBoxStyle.Information, "Record Added")
End Sub

1 个答案:

答案 0 :(得分:3)

错误是包含空格的表的名称,因此您需要将其括在方括号中

INSERT INTO [Student Details] ........

但你真的需要知道如何使用参数化查询 此代码实际上是对Sql Injections

的邀请

这是您可以修改代码以使用参数化查询的方法

Dim InsertString As String
InsertString = "Insert into [STUDENT DETAILS] "  & _
"(SREGNO,SFIRSTNAME,SMIDDLENAME,SLASTNAME,SYEAR,SCOURSE,SSEM,SCLASS,SLANGUAGE)" & _
"Values(?,?,?,?,?,?,?,?,?)"
Dim InsertCommand As New OleDbCommand(InsertString, Con)
InsertCommand.Parameters.AddWithValue("@p1", Me.TXTSREGNO.Text )
InsertCommand.Parameters.AddWithValue("@p2", Me.TXTSFIRSTNAME.Text )
InsertCommand.Parameters.AddWithValue("@p3", Me.TXTSMIDDLENAME.Text )
InsertCommand.Parameters.AddWithValue("@p4", Me.TXTSLASTNAME.Text )
InsertCommand.Parameters.AddWithValue("@p5", Me.COMB1SYEAR.Text )
InsertCommand.Parameters.AddWithValue("@p6", Me.COMB2SCOURSE.Text) 
InsertCommand.Parameters.AddWithValue("@p7", Me.COMB3SSEM.Text)
InsertCommand.Parameters.AddWithValue("@p8", Me.COMB4SCLASS.Text )
InsertCommand.Parameters.AddWithValue("@p9", Me.COMB5SLANGUAGE.Text)
InsertCommand.ExecuteNonQuery()

是的,您必须编写更多代码,但它对于Sql Injection更安全,当您的一个或多个文本框字段恰好包含单引号时,您将永远不会遇到语法错误。