1

我正在尝试将图像插入到我的 MS Access 2007 数据库中。我选择的数据类型是“OLEObject”,字段名是“Image”。我尝试了以下在按下按钮时执行的代码:

Private Sub ButtonPress()

    Dim cmd As New OleDbCommand
    Dim MemStream As New IO.MemoryStream
    Dim DataPic_Update As Byte()
    Dim strImage As String

    If Not IsNothing(PictureBox1.Image) Then

        PictureBox1.Image.Save(MemStream, Imaging.ImageFormat.Png)
        DataPic_Update = MemStream.GetBuffer
        MemStream.Read(DataPic_Update, 0, MemStream.Length)
        strImage = "?"
        MemStream.Close()

    Else
        DataPic_Update = Nothing
        strImage = "NULL"
    End If

    con.Open()

    cmd.CommandText = "INSERT INTO Inventory([Image])" + "VALUES(@Image)"

    cmd.Parameters.Add("@Image", OleDbType.Binary).Value = DataPic_Update
    cmd.Connection = con
    cmd.ExecuteNonQuery()
    con.Close()

End Sub

执行命令“ExecuteNonQuery”时,出现以下错误:

“标准表达式中的数据类型不匹配。”

我无法解决此错误。有人可以帮我解决现有代码中所需的任何建议或修改吗?我想插入图像,然后从访问数据库中检索。

4

2 回答 2

0

无需连接 cmd.CommandText,“([Image])”和“VALUES(@Image)”之间缺少一个空格,因此生成的查询是:

“插入库存([图片])值(@图片)”

代替

“插入库存([Image])值(@Image)”

不需要围绕“图像”的括号,因为该字段不包含空格,也不是保留关键字。

检查您是否具有在访问中嵌入二进制文件所需的所有依赖项。这种依赖关系有时不是很清楚,例如,我记得在带有 Access XP 的 Windows XP 中,您需要安装 Paintbrush 才能完成此操作。

于 2013-09-02T13:14:42.443 回答
0

我会建议您使用我在 Access 数据库上测试的以下代码:

Private Function ReadFile(sPath As String) As Byte()
    'Initialize byte array with a null value initially.
    Dim data As Byte() = Nothing

    'Use FileInfo object to get file size.
    Dim fInfo As New FileInfo(sPath)
    Dim numBytes As Long = fInfo.Length
    'Open FileStream to read file
    Dim fStream As New FileStream(sPath, FileMode.Open, FileAccess.Read)
    'Use BinaryReader to read file stream into byte array.
    Dim br As New BinaryReader(fStream)
    'When you use BinaryReader, you need to supply number of bytes to read from file.
    'In this case we want to read entire file. So supplying total number of bytes.
    data = br.ReadBytes(CInt(numBytes))
    fStream.Close()
    fStream.Dispose()
    Return data
End Function

以及将图像保存到 MS Access 数据库的代码

 Dim logo() As Byte = ReadFile("E:\logo.jpg")
    ' Update(23373, logo)
    Try
        Dim CN As New OleDbConnection(Str_Conn)
        CN.Open()
        Dim cmd As New OleDbCommand("Update TblInventory Set Image=@img Where Image_ID=@id", CN)
        cmd.Connection = CN

        cmd.Parameters.Add(New OleDbParameter("@finger", DirectCast(logo, Object)))

        cmd.Parameters.AddWithValue("@id", 51384)
        cmd.ExecuteNonQuery()
        CN.Close()
    Catch ex As Exception
        MessageBox.Show("Error Occured while Registering Finger Prints, Try Again" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    End Try

重要提示:您必须以您在查询中提到的相同序列传递参数。

于 2015-08-10T17:11:14.330 回答