Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

Simple Method to Save Image in Database

1.67/5 (3 votes)
29 Aug 2013CPOL 19.6K  
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:

SQL
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:
    SQL
    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:

    SQL
    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();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)