65.9K
CodeProject is changing. Read more.
Home

Simple Method to Save Image in Database

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.67/5 (3 votes)

Aug 29, 2013

CPOL
viewsIcon

19640

This tip shows you how to insert image in database.

Introduction

This tip shows you how to insert an image in database. It is a basic and simple method to store an image in SQL Server database.

First, create a table named image in database using the following code:

CREATE TABLE [dbo].[image](
	[img] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Open a new form in Visual Studio:

  1. Get a groupbox.
  2. Insert a picture box inside groupbox.
  3. Set dock property of picturebox to fill.
  4. The code for upload image in picturebox is as follows:
    private void button1_Click(object sender, EventArgs e)
            {
                OpenFileDialog fop = new OpenFileDialog();
                fop.InitialDirectory = @"C:\";
                fop.Filter = "[JPG,JPEG]|*.jpg";
                if (fop.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(fop.FileName);
                    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                    pictureBox1.Refresh();
                }
            }
  5. The code for save button to save image in database is as follows:

    string strConn = "Data Source= System Name;
    Initial Catalog=Database Name; User Id=your user id; Password= your password";
                SqlConnection Con = new SqlConnection(strConn);
                Con.Open();
                string strCmd = "insert into image (img) values ('" + pictureBox1.Image + "' )"   ;
                SqlCommand Cmd = new SqlCommand(strCmd, Con);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, Con);
                DataSet ds = new DataSet();
                Cmd.ExecuteNonQuery();
                MessageBox.Show("success");
                Con.Close();