VB.NET: Retrive an image (blob) from MySQL DB

ぃ、小莉子 提交于 2019-12-13 06:04:36

问题


I've a field called "Foto" in MySQL DB. This field is a blob. When I used SQL Server, the following code worked:

    Dim conn As New MySqlConnection
    conn.ConnectionString = ConnectionString
    Dim cmd As New MySqlCommand
    cmd.Connection = conn
    conn.Open()
    cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"
    Dim reader As MySqlDataReader

        reader = cmd.ExecuteReader
        While reader.Read
            If (IsDBNull(reader("Foto"))) Then
                frmCartaIdentitaView.pctImage.Image = Nothing
            Else
                Dim byteImage() As Byte = reader("Foto")
                Dim frmImageView stmFoto As New System.IO.MemoryStream(byteImage)
                frmImageView.pctImage.Image = Image.FromStream(stmFoto)
                frmImageView.pctImage.SizeMode = PictureBoxSizeMode.Zoom
                frmImageView.Show()
            End If
        End While

But now that I'm using mysql, is produced the following error: invalid parameter.


回答1:


If your ID field is an integer, see if this gets you past that error. Instead of this:

cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"

Try this:

cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = " & ctype(int32,IDtxt).ToString



回答2:


I had the same problem. I got this error when the BLOB column was empty, then I solved this way: Sorry, but I found this post just now

Dim conn As New MySqlConnection
conn.ConnectionString = ConnectionString
Dim cmd As New MySqlCommand
cmd.Connection = conn
conn.Open()
cmd.CommandText = "SELECT Foto, length(Foto) AS picLen FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"
Dim reader As MySqlDataReader

    reader = cmd.ExecuteReader
    While reader.Read
        If (reader("picLen "))=0 Then
            frmCartaIdentitaView.pctImage.Image = Nothing
        Else
            Dim byteImage() As Byte = reader("Foto")
            Dim frmImageView stmFoto As New System.IO.MemoryStream(byteImage)
            frmImageView.pctImage.Image = Image.FromStream(stmFoto)
            frmImageView.pctImage.SizeMode = PictureBoxSizeMode.Zoom
            frmImageView.Show()
        End If
    End While


来源:https://stackoverflow.com/questions/18977554/vb-net-retrive-an-image-blob-from-mysql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!