How to Save an Image in the MySQL Database Using C#

This one is the continuation of my previous tutorial which is How to Load an Image from the Local Directory into the PictureBox in C#. This tutorial will show you how to save an image in the mysql database using c#. In this method you will be able to save any image that you like that is available from the Local Directory to MySQL Database. See the procedure below.

Creating Database

Create a database and named it “dbsaveimage”. Create a table in the database that you have created
  1. CREATE TABLE `tblgalery` (
  2.   `ID` int(11) NOT NULL,
  3.   `myImage` longblob NOT NULL

Creating Application

Step 1

Open the file How to Load an Image from the Local Directory into the PictureBox in C#.

Step 2

Add a Button in the Form. saveimage321

Step 3

Double click the “Save Image” button to fire the click event handler of it and do the following codes for saving an image in the MySQL database.
  1. string strconnection = "Server=localhost;User Id=root;password=janobe;database=dbsaveimage;sslMode=none;";
  2.  
  3.             MySqlConnection con = new MySqlConnection(strconnection) ;
  4.             try
  5.             {
  6.                     con.Open();
  7.                     using (MySqlCommand cmd = new MySqlCommand("INSERT INTO tblgalery (myImage) VALUES (@IM)", con))
  8.                     {
  9.                         string path = openFileDialog1.FileName;
  10.                         byte[] imageData = File.ReadAllBytes(@path);
  11.                         cmd.Parameters.AddWithValue("@IM", imageData);
  12.                         cmd.ExecuteNonQuery();
  13.                     }
  14.                     MessageBox.Show("Image has been saved in the database.");
  15.             }
  16.             catch(Exception ex)
  17.             {
  18.                 MessageBox.Show(ex.Message);
  19.             }
  20.             finally
  21.             {
  22.                 con.Close();
  23.             }
  24.                  
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment