无法从Vb.net中的SQL Server检索图像

时间:2014-01-18 23:41:40

标签: vb.net sql-server-2008

我有一个数据库,其字段名称如下,并且在同一个表中,它还有一个字段名称“photo”,并且数据类型为Varbinary(max)

我在存储图像时没有遇到任何问题,但是当我试图从我的数据库中显示图像文件时,它没有显示任何内容,我得到一个错误“无法将类型为'System.String'的对象强制转换为'System.Byte [ ]”。“

Sub fillDataFields()
    Dim mid As String
    Dim last As String
    Dim first As String
    con.Open()
    comm.CommandText = "Select last_name,middle_name,first_name,course, section, address, birthday, picture from Users where user_id like '%" & frmUsers.ListView1.SelectedItems(0).Text & "%'"
    comm.Connection = con
    Dim imageData As Byte() = DirectCast(comm.ExecuteScalar(), Byte())
    If Not imageData Is Nothing Then
        Using ms As New MemoryStream(imageData, 0, imageData.Length)
            ms.Write(imageData, 0, imageData.Length)
            PictureBox1.BackgroundImage = Image.FromStream(ms, True)
        End Using
    End If
    dr = comm.ExecuteReader
    While (dr.Read())
        last = (dr("last_name"))
        mid = (dr("middle_name"))
        first = (dr("first_name"))
        txtCourse.Text = (dr("course"))
        txtSection.Text = (dr("section"))
        richtxtAddress.Text = (dr("address"))
        txtBirthday.Text = (dr("birthday"))
        txtName.Text = last + ", " + first + " " + mid
    End While

    con.Close()
    dr.Close()
    comm.Dispose()
End Sub

1 个答案:

答案 0 :(得分:2)

您尝试使用ExecuteScalar提取图像数据,但此方法会返回第一行的第一列,并且在您的查询中,此数据是字段Last_Name的内容。这是错误的原因

说,我想你应该把你的逻辑应用到字段图片的内容

Sub fillDataFields()
    Dim mid As String
    Dim last As String
    Dim first As String

    con.Open()
    comm.CommandText = "Select last_name,middle_name,first_name,course, section, address, " & _
                       "birthday, picture from Users where user_id like @uid"
    comm.Connection = con
    comm.Parameters.AddWithValue("@uid", "%" & frmUsers.ListView1.SelectedItems(0).Text & "%")
    dr = comm.ExecuteReader
    While (dr.Read())
        last = (dr("last_name"))
        mid = (dr("middle_name"))
        first = (dr("first_name"))
        txtCourse.Text = (dr("course"))
        txtSection.Text = (dr("section"))
        richtxtAddress.Text = (dr("address"))
        txtBirthday.Text = (dr("birthday"))
        txtName.Text = last + ", " + first + " " + mid

        Dim imageData As Byte() = DirectCast(dr("picture"), Byte())
        If Not imageData Is Nothing Then
            Using ms As New MemoryStream(imageData, 0, imageData.Length)
               ms.Write(imageData, 0, imageData.Length)
               PictureBox1.BackgroundImage = Image.FromStream(ms, True)
           End Using
        End If
    End While
    con.Close()
    dr.Close()
    comm.Dispose()
End Sub

请注意,我还删除了字符串连接,因为它是一个安全性rìsk(Sql Injection)。您还应该修改此代码以应用using statement

所需的逻辑