Introduction
In this article we will first 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 in the database, here is the script for the table:
- CREATE TABLE `image` (
- `name` varchar(100) default NULL,
- `type` varchar(100) default NULL,
- `desc` varchar(100) default NULL,
- `docname` varchar(5000) default NULL,
- `docdisc` varchar(500) default NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1
Create a new Windows Forms application and arrange controls on the form as in the following:
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 be saved in the database:
-
- String location;
-
-
- String fileName;
- private void Browse_Click(object sender, EventArgs e)
- {
- openPic.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
-
- openPic.ShowDialog();
-
- pictureBox1.BackgroundImage = new Bitmap(openPic.FileName);
-
- location = openPic.FileName;
- textBox2.Text = location;
-
- fileName = openPic.SafeFileName;
- }
Write the following code in the Click event of the btnSave Button:
- private void btn_SaveImage_Click(object sender, EventArgs e)
- {
- MySqlConnection con = new MySqlConnection(ConString);
- MySqlCommand cmd;
- FileStream fs;
- BinaryReader br;
- try
- {
-
- FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read);
-
-
- int fileLength = (int)fs.Length;
-
-
- byte[] rawdata = new byte[fileLength];
-
-
-
- fs.Read(rawdata, 0, (int)fileLength);
-
-
- MySqlCommand cmd = new MySqlCommand();
-
-
- String sql = "insert into doc1 values(@pfno,@depname,@doctype,@docdesc,@docexpdate,@docname,@docdisc)";
-
-
- con = new MySqlConnection();
- con.ConnectionString = ConfigurationSettings.AppSettings["constr"];
- con.Open();
-
-
- cmd = new MySqlCommand(sql, con);
-
-
-
-
-
-
- cmd.Parameters.AddWithValue("@name", label8.Text);
- cmd.Parameters.AddWithValue("@type", comboBox1.Text);
- cmd.Parameters.AddWithValue("@desc", textBox1.Text);
- cmd.Parameters.AddWithValue("@docname", textBox2.Text);
- cmd.Parameters.AddWithValue("@docdisc", fileLength);
-
- cmd.ExecuteNonQuery();
-
- con.Close();
- MessageBox.Show("Done");
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
The comments are given in // blocks.