Click here to Skip to main content
15,888,255 members
Articles / Programming Languages / SQL
Tip/Trick

Simple Method to Save Image in Database

Rate me:
Please Sign up or sign in to vote.
1.67/5 (3 votes)
29 Aug 2013CPOL 19.4K   2   2
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)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Vijay Gill29-Aug-13 23:08
professionalVijay Gill29-Aug-13 23:08 
GeneralMy vote of 1 Pin
Mehdi Gholam29-Aug-13 19:41
Mehdi Gholam29-Aug-13 19:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.