从数据库中获取图片(关闭)

时间:2014-09-17 04:40:34

标签: vb.net

这是我的成功代码:

     Private Sub dg1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dg1.CellContentClick
    Label5.Text = dg1.Item(0, e.RowIndex).Value
    Label6.Text = dg1.Item(2, e.RowIndex).Value
    con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\USER\DOWNLOADS\SDP(BACKUP1)\SDP(BACKUP)\SDP.MDF;Integrated Security=True"
    con.Open()
    cmd.Connection = con
    cmd.CommandText = "select picture from Announcement where name = @name"
    cmd.Parameters.AddWithValue("@name", dg1.CurrentRow.Cells(0).Value())
    da.SelectCommand = cmd

    Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
    If Not imageData Is Nothing Then
        Using ms As New MemoryStream(imageData, 0, imageData.Length)
            ms.Write(imageData, 0, imageData.Length)
            PictureBox2.Image = Image.FromStream(ms, True)
        End Using
    End If
End Sub

我成功从数据库中获取了我的照片。将paramater添加到name,然后使用@name添加参数名称。

1 个答案:

答案 0 :(得分:1)

您根本没有加载DataGridView的图片。您正在尝试查询数据库,但它失败了。与网格或图像无关。简单明了,你编写了错误的SQL代码。如果你要包含一个文本文字,那么它需要在它周围加上单引号。更好的是,正确地使用参数。

正如我所说,问题在于您的SQL代码:

cmd.CommandText = "select picture from Announcement where name =" & dg1.Item(0, e.RowIndex).Value & ""

您正在将name列的值插入到该SQL代码中,以便它成为文本文字。正如我所说,文字文字需要单引号。你的单引号在哪里?你没有。这就是问题所在。如果你打算使用这样的字符串连接,你不应该这样,那么它需要看起来像这样:

cmd.CommandText = "select picture from Announcement where name = '" & dg1.Item(0, e.RowIndex).Value & "'"

如果你要正确地做,这涉及使用参数,正如我所说,那么它看起来像这样:

cmd.CommandText = "select picture from Announcement where name = @name"
cmd.Parameters.AddWithValue("@name", CStr(dg1.Item(0, e.RowIndex).Value))

或者像这样:

cmd.CommandText = "select picture from Announcement where name = @name"
cmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = CStr(dg1.Item(0, e.RowIndex).Value)
相关问题