I found lots of question in MSDN on how to save and retrieve image data from SQL server, so posting codes that might help others. I am using VarBinary(Max) data type for Images sinceImage datatype is being abandoned by sql team.
| Dim myfilelocation As String = "C:\myPictures\myimage.jpg" |
| Dim conn As New SqlConnection("Data Source= .\sqlexpress; Initial Catalog=Temp;Integrated Security =True") |
| Dim cmd As New SqlCommand("Insert Into ImageTable(ImageFile,CustomerID) Values (@ImageData,@CustomerID)", conn) |
| |
| Dim param As New SqlParameter("@ImageData", SqlDbType.VarBinary) |
| Dim ImageData As Byte() = IO.File.ReadAllBytes(myfilelocation) |
| param.Value = ImageData |
| cmd.Parameters.Add(param) |
| |
| cmd.Parameters.AddWithValue("@CustomerID", 3) |
| Try |
| conn.Open() |
| cmd.ExecuteNonQuery() |
| Catch ex As Exception |
| MessageBox.Show(ex.Message) |
| Finally |
| conn.Close() |
End Try
|
And Retrieve part
Dim conn As New SqlConnection("Data Source= .\sqlexpress; Initial Catalog=Temp;Integrated Security =True") |
| Dim cmd As New SqlCommand("select ImageFile from ImageTable where CustomerID=@CustomerID ", conn) |
| cmd.Parameters.AddWithValue("@CustomerID", 3) |
| Try |
| conn.Open() |
PictureBox1.Image = Image.FromStream(New IO.MemoryStream(CType(cmd.ExecuteScalar, Byte()))) ' or you can save in a file 'IO.File.WriteAllBytes("c:\backup\image3.jpg", CType(cmd.ExecuteScalar, Byte()))
|
| Catch ex As Exception |
| MessageBox.Show(ex.Message) |
| Finally |
| conn.Close() |
| End Try |
367884c8-4c2d-44a7-b30c-1e7abc0f62d0|0|.0