Friday 1 June 2012

Save an Image in SQL Server Database With VB.Net

Hi
Saving Image is an important part of any software,They're many ways to handling image.One easy and secure way is save your image in sql server database.If you want to save image in sql server then follow these steps
  • Make a database and a table with following description my database name is bsw and table name is stu
Database Table Structure

VB Project Controls Which you have to use
  •  You have to import 2 name space
    Imports System.IO
    Imports System.Data.SqlClient
  • Add OpenFileDialog control
  • And make a global string variable named str
    • On Browse picture button click paste following code
        OpenFileDialog1.ShowDialog()
         str = OpenFileDialog1.FileName
On Click event of save button paste following code


Dim con As New SqlConnection("initial catalog=bsw;data source=.;integrated security=true") Dim com As New SqlCommand()
Try
            Dim fs As New        FileStream(str,FileMode.Open)
            Dim data() As Byte = New [Byte](fs.Length) {}
            fs.Read(data, 0, fs.Length)
            fs.Close()
            'readed image
            Dim roll As New SqlParameter("roll", SqlDbType.Int)
            roll.Value = Val(TextBox1.Text)

            Dim name As New SqlParameter("name", SqlDbType.Char, 10)
            name.Value = TextBox2.Text

            Dim city As New SqlParameter("city", SqlDbType.Char, 10)
            city.Value = TextBox3.Text

            Dim img As New SqlParameter("img", SqlDbType.Image)
            img.Value = data
            'Adding parameters
            com.Parameters.Add(roll)
            com.Parameters.Add(name)
            com.Parameters.Add(city)
            com.Parameters.Add(img)
            con.Open()
            com.Connection = con
            com.CommandText = "insert into stu values(@roll,@name,@city,@img)"
            com.ExecuteNonQuery()
            MsgBox("Saved")
            Me.StuTableAdapter.Fill(Me.BswDataSet1.stu)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

No comments:

Post a Comment