Read Mediumblob data type from MYSQL in C#

回眸只為那壹抹淺笑 提交于 2019-12-23 20:25:38

问题


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.


回答1:


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...



来源:https://stackoverflow.com/questions/13047099/read-mediumblob-data-type-from-mysql-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!