Storing Images in MySQL database

We may need to store the images in the database. It is easy and pretty simple.

The basic idea is;
1) The images are stored in database as bytes. In MySQL database we need to create a field/column of type "Blob".
2) Need to use FileStream and BinaryReader objects to convert images into bytes.

Here is the C# code, to do the task

Table schema:

C# code:
MySqlConnection mcon = null;
MySqlCommand cmd = null;
FileStream fsObj = null;
BinaryReader binRdr = null;
try
{
//converting image to bytes
fsObj = File.OpenRead(pictureBox1.ImageLocation);
byte[] imgContent = new byte[fsObj.Length];
binRdr = new BinaryReader(fsObj);
imgContent = binRdr.ReadBytes((int)fsObj.Length);
mcon = new MySqlConnection("server=localhost;user=root;pwd=root;database=test;");
mcon.Open();
//inserting into MySQL db
cmd = new MySqlCommand("insert into users (userid,username,userphoto) values (@userid, @username, @userphoto)", mcon);
cmd.Parameters.Add(new MySqlParameter("@userid", (object)textBox1.Text));
cmd.Parameters.Add(new MySqlParameter("@username", (object)textBox2.Text));
cmd.Parameters.Add(new MySqlParameter("@userphoto", (object)imgContent));
MessageBox.Show(cmd.ExecuteNonQuery().ToString() + " rows affected");
}
catch (MySqlException mex)
{
MessageBox.Show(mex.Message);
}
finally
{
if (binRdr != null)binRdr.Close();
binRdr = null;

if (fsObj != null)fsObj.Close();
fsObj = null;
if (cmd != null)cmd.Dispose();
cmd = null;

if (mcon != null)
{
if (mcon.State == ConnectionState.Open)
mcon.Close();
}
}

The above code will export the selected image into MySQL database. Please note that based on the image size we may need to define the blob datatype as "tinyblob", "blob", "mediumblob"or "longblob".


Comments

Post a Comment

Popular posts from this blog

XML Documentation comments

DataTable ExtendedProperties