Inserting & retrieving images from SQL Server database using stored procedures

Objective:

To insert & retrieve images from SQL server database using stored procedures and also to perform insert, search, update and delete operations & navigation of records.

Introduction:

As we want to insert images into database using stored procedures, we have to create a table and stored procedures in the database.

Query for creating table in our application:

create table student(sno int primary key,sname varchar(50),course varchar(50),fee money,photo image)

Stored procedures:

create procedure  get_student
as
select  sno,sname, course, fee, photo from student 

-----------

create procedure insert_student (@sno int, @sname varchar(50), @course varchar(50), @fee smallmoney,@photo image=null) 
as 
insert into student(sno, sname,course, fee, photo) values (@sno, @sname, @course, @fee, @photo) 

---------------

create procedure  update_student(@sno int, @sname varchar(50),@course varchar(50), @fee smallmoney,@photo image=null) 
as
update student set sname=@sname, course=@course, fee=@fee, photo=@photo where sno=@sno

------------

create procedure delete_student(@sno int=null)
as
if not(@sno=null)
delete from student where sno=@sno

---------------------------------------------
 
Design:

1.gif
 
Design the form as above with 1 PictureBox control, 1 OpenFileDialog control, 4 Labels, 4 TextBoxes and 11 Buttons.

PictureBox1 Properties:

    BorderStyle=Fixed3D; SizeMode=StrechImage

Note that OpenFileDialog control appears below the form (not on the form).

Introduction to code:

In order to communicate with SQL sever database, include the namespace using System.Data.SqlClient.

In this application, we will search a record by taking input from the InputBox. For this we have to add reference to Microsoft.VisualBasic.

Adding a Reference to 'Microsoft.VisualBasic':

Goto Project Menu ->Add Reference -> select 'Microsoft.VisualBasic' from .NET tab.

In order to use this reference we have to include the namespace: 'using Microsoft.VisualBasic' in the code.

Converting image into binary data: 

We can't store an image directly into the database. For this we have two solutions:

i) To store the location of the image in the database

ii) Convert the image into binary data and insert that binary data into database and convert that back to image when retrieving the records.

If we store the location of an image in the database, and suppose if that image is deleted or moved from that location, we will face problems while retrieving the records. So it is better to convert image into binary data and insert that binary data into database and convert that back to image while retrieving records.

->We can convert an image into binary data using 1. FileStream (or) 2. MemoryStream

1. FileStream uses file location to convert an image into binary data which we may/may not provide when updating a record.

Ex:

FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open,FileAccess.Read);
byte[] photo_aray = new byte[fs.Length];
fs.Read(photo_aray, 0, photo_aray.Length);

2. So it is better to use MemoryStream which uses image in the PictureBox to convert an image into binary data.

Ex:

MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);

->In order to use FileStream or MemoryStream we have to include the namespace: 'using System.IO'.
           
OpenFileDialog Control:

We use OpenFileDialog control to browse for the images (photos) to insert into the record.

Using DataAdapter with StoredProcedures:

We can use command object to work with stored procedures by passing stored procedure name to command object and specifying CommandType as StoredProcedure

Ex:

cmd = new SqlCommand("get_student", con);
cmd.CommandType = CommandType.StoredProcedure;

DataAdapter can't interact directly with the stored procedures, but if we need to use DataAdapter while working with stored procedures, we can achieve this by passing the command object to the DataAdapter.

Loading the constraint details into the dataTable:

In this app. we use Find() method to search a record, which requires details of primarykey column, which can be provided using the statement: 

adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

Pointing to current record in dataTable:

After searching a record, we have to get the index of that record so that we can show next and previous records when we press '>>'(next) and '<<'(previous) buttons.

Ex:

rno= ds.Tables[0].Rows.IndexOf(drow);

Code:

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.VisualBasic;

namespace inserting_imgs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter adapter;
        DataSet ds; int rno = 0;
        MemoryStream ms;
        byte[] photo_aray;
        private void Form1_Load(object sender, EventArgs e)
        {
            con = new SqlConnection("user id=sa;password=123;database=prash");
            loaddata();
            showdata();
        }
        void loaddata()
        {
            cmd = new SqlCommand("get_student", con);
            cmd.CommandType = CommandType.StoredProcedure; adapter = new SqlDataAdapter(cmd);
            adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            ds = new DataSet(); adapter.Fill(ds, "student");
        }
        void showdata()
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                textBox1.Text = ds.Tables[0].Rows[rno][0].ToString();
                textBox2.Text = ds.Tables[0].Rows[rno][1].ToString();
                textBox3.Text = ds.Tables[0].Rows[rno][2].ToString();
                textBox4.Text = ds.Tables[0].Rows[rno][3].ToString();
                pictureBox1.Image = null;
                if (ds.Tables[0].Rows[rno][4] != System.DBNull.Value)
                {
                    photo_aray = (byte[])ds.Tables[0].Rows[rno][4];
                    MemoryStream ms = new MemoryStream(photo_aray);
                    pictureBox1.Image = Image.FromStream(ms);
                }
            }
            else
                MessageBox.Show("No Records");
        }
        private void browse_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
            DialogResult res = openFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
            }
        }
        private void clear_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";
            pictureBox1.Image = null;
        }
        private void insert_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("insert_student", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@sno", textBox1.Text);
            cmd.Parameters.AddWithValue("@sname", textBox2.Text);
            cmd.Parameters.AddWithValue("@course", textBox3.Text);
            cmd.Parameters.AddWithValue("@fee", textBox4.Text);
            conv_photo();
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("record inserted");
                loaddata();
            }
            else
                MessageBox.Show("insertion failed");
        }
        void conv_photo()
        {
            //converting photo to binary data
            if (pictureBox1.Image != null)
            {
                ms = new MemoryStream();
                pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
                byte[] photo_aray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(photo_aray, 0, photo_aray.Length);
                cmd.Parameters.AddWithValue("@photo", photo_aray);
            }
        }
        private void search_Click(object sender, EventArgs e)
        {
            try
            {
                int n = Convert.ToInt32(Interaction.InputBox("Enter sno:", "Search", "20", 100, 100));
                DataRow drow;
                drow = ds.Tables[0].Rows.Find(n);
                if (drow != null)
                {
                    rno = ds.Tables[0].Rows.IndexOf(drow);
                    textBox1.Text = drow[0].ToString();
                    textBox2.Text = drow[1].ToString();
                    textBox3.Text = drow[2].ToString();
                    textBox4.Text = drow[3].ToString();
                    pictureBox1.Image = null;
                    if (drow[4] != System.DBNull.Value)
                    {
                        photo_aray = (byte[])drow[4];
                        MemoryStream ms = new MemoryStream(photo_aray);
                        pictureBox1.Image = Image.FromStream(ms);
                    }
                }
                else
                    MessageBox.Show("Record Not Found");
            }
            catch
            {
                MessageBox.Show("Invalid Input");
            }
        }
        private void update_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("update_student", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@sno", textBox1.Text);
            cmd.Parameters.AddWithValue("@sname", textBox2.Text);
            cmd.Parameters.AddWithValue("@course", textBox3.Text);
            cmd.Parameters.AddWithValue("@fee", textBox4.Text);
            conv_photo();
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("Record Updated");
                loaddata();
            }
            else
                MessageBox.Show("Updation Failed");
        }
        private void delete_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("delete_student", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@sno", textBox1.Text);
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("Record Deleted");
                loaddata();
                rno = 0;
                showdata();
            }
            else
                MessageBox.Show("Deletion Failed");
        }
        private void first_Click(object sender, EventArgs e)
        {
            rno = 0; showdata();
            MessageBox.Show("First record");
        }
        private void previous_Click(object sender, EventArgs e)
        {
            if (rno > 0)
            {
                rno--; showdata();
            }
            else
                MessageBox.Show("First record");
        }
        private void next_Click(object sender, EventArgs e)
        {
            if (rno < ds.Tables[0].Rows.Count - 1)
            {
                rno++; showdata();
            }
            else
                MessageBox.Show("Last record");
        }
        private void last_Click(object sender, EventArgs e)
        {
            rno = ds.Tables[0].Rows.Count - 1;
            showdata(); MessageBox.Show("Last record");
        }
        private void exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Up Next
    Ebook Download
    View all
    Learn
    View all