Picture Insertion:
How to insert a picture into a SQL Server 2005 database by using vb.net2008? I need code with explanation, for example I have a database table where I want to store a picture ..
I have no idea to store image in SQL Server 2005, how can I do that?
Please help me ...
My current code is not right plz check it and tell e new simple code for insert image:
My code
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("Data Source=nida-PC\SQLEXPRESS;AttachDbFilename=" & path & "Database1.mdf;Integrated Security=True;User Instance=True")
'Dim con As New SqlConnection= ("Data Source=NIDA-PC\SQLEXPRESS;Initial Catalog=Finaldb;Integrated Security=True")
Dim cmd As SqlCommand
' Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
'PictureBox1.BackgroundImage = Image.FromFile(OpenFileDialog1.FileName)
'Label1.Visible = True
'TextBox1.Visible = True
'Label1.Text = "Name"
'TextBox1.Text = ("Save image")
' End If
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.InformationTableAdapter.Fill(Me.Database1DataSet.Information)
con.Open()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.BackgroundImage = Image.FromFile(OpenFileDialog1.FileName)
Label1.Visible = True
TextBox1.Visible = True
Label1.Text = "Name"
TextBox1.Clear()
PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
If TextBox1.Text = "" Then
MsgBox("Fill the Name Field")
Else
Dim sql As String = "Insert into tbl_image(@Image_Name,@photo)"
Dim cmd As New SqlCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("@Image_Name", TextBox1.Text)
cmd.Parameters.AddWithValue("@Photo", SqlDbType.Image)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("@photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
'Form1_Load(sender, e)
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
Label1.Visible = False
TextBox1.Visible = False
End If
Catch ex As Exception
'MsgBox("")
Return
End Try
con.Close()
End Sub
Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox1.Enter
End Sub
End Class
You can insert a image in database by using following query:
"D:\Desktop\xyz" replace it with your file path.