在C#中从MYSQL读取Mediumblob数据类型 [英] Read Mediumblob data type from MYSQL in C#

查看:151
本文介绍了在C#中从MYSQL读取Mediumblob数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MYSQL Server中有一个数据库.有一个表,用于存储包含其信息的图像.该图像的数据类型为Mediumblob.我需要读取它并存储在byte []中,但是我不知道该怎么做.有人针对这种情况有解决方案吗?非常感谢:)

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 :)

致谢.

推荐答案

查看

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

要存储图像:

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格式存储),但是您可以对数据进行任何操作...

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

这篇关于在C#中从MYSQL读取Mediumblob数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆