Private Sub btnAddRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddRecord.Click
Dim arrImage() As Byte
Dim strImage As String
Dim myMs As New IO.MemoryStream
'
If Not IsNothing(Me.PictureBox2.Image) Then
Me.PictureBox2.Image.Save(myMs, Me.PictureBox2.Image.RawFormat)
arrImage = myMs.GetBuffer
strImage = "?"
Else
arrImage = Nothing
strImage = "NULL"
End If
Dim Conn As New OleDbConnection("Provider=Microsoft.ACE.OleDB.12.0; Data Source=|DataDirectory|\Student_Records.accdb")
Conn.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = Conn
cmd.CommandText = "INSERT INTO Student_Information(Surname, First, Last, Department,Session, [Mat_Num], Picture) VALUES(" & Me.txtSurname.Text & ",'" & Me.txtFirst.Text & ",'" & Me.txtLast.Text & ",'" & Me.txtDeaprtment.Text & ",'" & Me.txtSession.Text & ",'" & Me.txtMat_Num.Text & "'," & strImage & ")"
If strImage = "?" Then
cmd.Parameters.Add(strImage, OleDb.OleDbType.Binary).Value = arrImage
End If
cmd.ExecuteNonQuery()
Conn.Close()
End Sub
INSERT INTO语句中的语法错误始终显示。
请问有什么问题?
答案 0 :(得分:2)
您的查询中有两个问题。
第一个很容易修复。单词FIRST,SESSION和LAST是Access中的保留关键字,如果您想将它们用于您的列,那么您应将它们括在方括号中
cmd.CommandText = "INSERT INTO Student_Information" & _
"(Surname, [First], [Last], Department, [Session], ....."
第二个问题更复杂,更严重。如果要构建sql命令,请不要使用字符串连接来构建命令。决不。
这是considered the GOTO of sql programming,因为它是Sql Injection(在Access上执行有点困难但仍然......)和解析问题等众多问题的根源。就像你在这里一样,因为你忘记在文本值周围使用引号。
唯一的解决方案是始终使用参数化查询
Dim cmdText= "INSERT INTO Student_Information" & _
"(Surname, [First], [Last], Department,[Session], [Mat_Num], Picture) " & _
"VALUES(@surname, @first, @last, @dep, @ses, @mat, @pic"
Using Conn = New OleDbConnection("...."
Using Cmd = new OleDbCommand(cmdText, Conn)
Conn.Open()
cmd.Parameters.Add("@surname", OleDbType.VarWChar).Value = Me.txtSurname.Text
cmd.Parameters.Add("@first", OleDbType.VarWChar).Value = Me.txtFirst.Text
cmd.Parameters.Add("@last", OleDbType.VarWChar).Value = Me.txtLast.Text
cmd.Parameters.Add("@dep", OleDbType.VarWChar).Value = Me.txtDeaprtment.Text
cmd.Parameters.Add("@ses", OleDbType.VarWChar).Value = Me.txtSession.Text
cmd.Parameters.Add("@mat", OleDbType.VarWChar).Value = Me.txtMat_Num.Text
cmd.Parameters.Add("@pic", OleDb.OleDbType.Binary).Value = arrImage
cmd.ExecuteNonQuery()
End Using
End Using
另请注意,连接和命令等每个一次性对象都应包含在Using语句中,以便在不再需要时正确关闭和销毁
答案 1 :(得分:0)
您缺少每个值的引号,无论如何最好使用参数:
cmd.CommandText = "INSERT INTO Student_Information(Surname, First, Last, Department,Session, [Mat_Num], Picture) VALUES(@param1,@param2,@param3,@param4,@param5,param6,@param7)"
cmd.Parameters.AddWithValue("@param1", Me.txtSurname.Text)
...
cmd.Parameters.AddWithValue("@param7", strImage)