How to save image in Ms-SQL Database using VB.NET

Imports System.Data.SqlClient

Dim connstring As String
Dim sql As String
Dim sqlcon As New SqlConnection

Private Sub SaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveImage.Click
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Length > 0 Then
connstring = "Data Source=localhost;Initial Catalog=Test;User id=username;password=password;"
sqlcon.ConnectionString = connstring
sqlcon.Open()

Dim imgByte As Byte() = Nothing

imgByte = IO.File.ReadAllBytes(OpenFileDialog1.FileName)

Dim sql As String = "INSERT INTO Image_Test(FieldName, FieldImage) VALUES(@parameter1, @parameter2)"
Dim cmd As SqlCommand = New SqlCommand(sql, sqlcon)
cmd.Parameters.AddWithValue("@parameter1", "TestValue")
cmd.Parameters.AddWithValue("@parameter2", imgByte)
cmd.ExecuteNonQuery()

sqlcon.Close()

End If
End Sub

No comments:

Post a Comment