How to Save Images in MySQL Database Using C#

In this article I will explain how to save images into a MySQL database in Windows Forms applications using C#.

Introduction

In this article first we will create a table in a MySQL database and then we will use a Windows Forms application to save an image into the database.

Description

Create a table in a MySQL database using MySQL browser as in the following. To store the image:

save-images-in-MySQL-database1.jpg

For storing images you can use any of the BLOB (Binary Large Object) data types based on your storage requirements. We are using the MEDIUMBLOB data type. The following are the storage capacities of various BLOB types in MySQL:

Data Type

Storage Capacity

BLOB

255 bytes

TINYBLOB

65,535 bytes (64 KB approx.)

MEDIUMBLOB

16,777,215 bytes (16 MB approx.)

LONGBLOB

4,294,967,295 bytes (4 GB approx.)

Create a new Windows Forms application and arrange controls on the form as in the following:

save-images-in-MySQL-database2.jpg

Add a reference to the MySql.Data dll using the Add Reference dialog box and include the following two namespaces:

using MySql.Data.MySqlClient;
using System.IO;

Write the following code in the Click event of PictureBox to select an image to save in the database:

private void pbStudentImage_Click(object sender, EventArgs e)

{

    try

    {

        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.Filter = "Image files | *.jpg";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)

        {

            txtStudentImage.Text = openFileDialog1.FileName;

            pbStudentImage.Image = Image.FromFile(openFileDialog1.FileName);

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message);

    }

}

Assign the same event to the Click and Enter events of the "txtStudentImage" TextBox , as in:

this.txtStudentImage.Click += new System.EventHandler(this.pbStudentImage_Click);
this.txtStudentImage.Enter += new System.EventHandler(this.pbStudentImage_Click);

Write the following code in the Click event of the btnSave Button:

private void btnSaveImage_Click(object sender, EventArgs e)

{

    MySqlConnection con = new MySqlConnection(ConString);

    MySqlCommand cmd;

    FileStream fs;

    BinaryReader br;

 

    try

    {

        if (txtFirstName.Text.Length > 0 && txtStudentImage.Text.Length > 0)

        {

            string FileName = txtStudentImage.Text;

            byte[] ImageData;

            fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);

            br = new BinaryReader(fs);

            ImageData = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

 

 

            string CmdString = "INSERT INTO Students(FirstName, LastName, Image, Address) VALUES(@FirstName, @LastName, @Image, @Address)";

            cmd = new MySqlCommand(CmdString, con);

 

            cmd.Parameters.Add("@FirstName", MySqlDbType.VarChar, 45);

            cmd.Parameters.Add("@LastName", MySqlDbType.VarChar, 45);

            cmd.Parameters.Add("@Image", MySqlDbType.Blob);

            cmd.Parameters.Add("@Address", MySqlDbType.VarChar, 100);

 

            cmd.Parameters["@FirstName"].Value = txtFirstName.Text;

            cmd.Parameters["@LastName"].Value = txtLastName.Text;

            cmd.Parameters["@Image"].Value = ImageData;

            cmd.Parameters["@Address"].Value = txtAddress.Text;

 

            con.Open();

            int RowsAffected = cmd.ExecuteNonQuery();

            if (RowsAffected > 0)

            {

                MessageBox.Show("Image saved sucessfully!");

            }

            con.Close();

        }

        else

        {

            MessageBox.Show("Incomplete data!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message);

    }

    finally

    {

        if (con.State == ConnectionState.Open)

        {

            con.Close();

        }

    }

}

Up Next
    Ebook Download
    View all
    Learn
    View all