我想将图片保存到数据库中

时间:2014-09-16 12:18:10

标签: vb.net

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Try
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        Dim a As New OpenFileDialog
        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 = "INSERT INTO Announcement ([name],[picture]) VALUES('" & nameTB.Text & "',@a2)"
        cmd.Parameters.Add(New SqlClient.SqlParameter("@a2", SqlDbType.Image)).Value = IO.File.ReadAllBytes(PictureBox2.BackgroundImage) 
        cmd.ExecuteNonQuery()
        MsgBox("Event Announcement submitted!")

        con.Close()
    Catch ex As Exception
        MsgBox("Operation Failed! Please Check Again!")
    End Try
End Sub

这是我尝试过的....我可以选择一个图像,但我不能保存它(这意味着完整保存图片到数据库)所有的东西在谷歌教我保存图片在SQL服务器或访问..我我试过了......但是我最不明白的事情是如何用picturebox参数@ a2? 它给IO.File.ReadAllBytes(PictureBox2.BackgroundImage)

带来错误

1 个答案:

答案 0 :(得分:0)

如评论所述,File.ReadAllBytes想要一个文件,而不是一个图像。所以你需要使用MemoryStream:

Using ms As New MemoryStream
  PictureBox2.BackgroundImage.Save(ms, ImageFormat.Png)
  cmd.Parameters.AddWithValue("@a2", ms.ToArray)
End Using