将图像插入访问数据库时出错

时间:2013-09-02 13:01:14

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

我正在尝试将图像插入MS Access 2007数据库。我选择的数据类型是" OLEObject"和Fieldname为" 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"时,我收到以下错误:

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

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

2 个答案:

答案 0 :(得分:0)

没有必要连接cmd.CommandText,“([Image])”和“VALUES(@Image)”之间缺少空格,因此生成的查询是:

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

而不是

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

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

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

答案 1 :(得分: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

重要说明:您必须在Query中提到的相同序列中传递参数。