Read Mediumblob data type from MYSQL in C#

byte, c#, mysql

Solution

Looking at the examples from this article on MySQL website, you should be able to handle the data like this:

To store the image:

MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;

// initialize "conn" and "cmd" here

FileStream fs = new FileStream(@"c:\image.png", FileMode.Open, FileAccess.Read);
FileSize = fs.Length;

byte[] rawData = new byte[FileSize];
fs.Read(rawData, 0, FileSize);
fs.Close();

conn.Open();

string SQL = "INSERT INTO file VALUES(NULL, @FileSize, @File)";

cmd.Connection = conn;
cmd.CommandText = SQL;
cmd.Parameters.AddWithValue("@FileSize", FileSize);
cmd.Parameters.AddWithValue("@File", rawData);

cmd.ExecuteNonQuery();

conn.Close();

And to read it:

MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader myData;

// initialize connection and query here...

myData = cmd.ExecuteReader();

if (!myData.HasRows)
    throw new Exception("There are no BLOBs to save");

myData.Read();

int FileSize = myData.GetUInt32(myData.GetOrdinal("file_size"));
byte[] rawData = new byte[FileSize];

myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, (int)FileSize);

FileStream fs = new FileStream(@"C:\newfile.png", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(rawData, 0, (int)FileSize);
fs.Close();

This code shows how to save the image into a file (and assumes it is stored in the PNG format) but you could do whatever you want with the data then...

Problem

I have a database in MYSQL Server. There's a table store an Image with its info. That image's data type is Mediumblob. I need to read it and store in a byte[] but I don't know how to do that.Anyone have a solution for this case? Tks so much :) Regards.

Original source