2014年4月30日 星期三

vbnet mssql varbinary Image

參考引用來源
--
Imports System.Data.SqlClient

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'save image
        Dim conn As New SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;")
        conn.Open()
        Dim cmd As New SqlCommand("INSERT INTO tableName (imageField) VALUES(@image)", conn)
        Dim p As New SqlParameter("@image", SqlDbType.VarBinary)
        Dim ms As New IO.MemoryStream
        PictureBox1.Image.Save(ms, Drawing.Imaging.ImageFormat.Png)
        p.Value = ms.ToArray
        cmd.ExecuteNonQuery()
        conn.Close()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'retrieve image
        Dim conn As New SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;")
        Dim cmd As New SqlCommand("SELECT imageField FROM tableName WHERE someField = @value", conn)
        Dim p As New SqlParameter("@value", SqlDbType.Int)
        p.Value = 1
        Dim o As Object = cmd.ExecuteScalar

        If o IsNot Nothing Then
            PictureBox1.Image = Image.FromStream(New IO.MemoryStream(DirectCast(o, Byte())))
        End If
    End Sub

End Class

沒有留言:

張貼留言