我在MYSQL Server中有一个数据库。有一个表存储一个图像及其信息。该图像的数据类型为Mediumblob。我需要阅读它并存储在一个字节[]但我不知道该怎么做。任何人都有这个案例的解决方案? Tks这么多:)
问候。
答案 0 :(得分:3)
查看this article on MySQL website中的示例,您应该能够像这样处理数据:
存储图像:
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();
阅读它:
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();
此代码显示如何将图像保存到文件中(并假设它以PNG格式存储),但您可以随意使用数据...