Mysql中的Blob类型可以存放字节数组,所以图片可以以字节数组得形式存储在其中。C#如何读取Blob类型的字段呢?其实与其它类型的读取方式一样。先将查询结果集放入DataTable中,然后遍历每行数据。对于Blob类型需要显示转换为byte[]。
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Security.Cryptography;
using MySql.Data.MySqlClient; // 引入MySQL驱动程序命名空间
class Program
{
static void Main()
{
string connectionString = "server=127.0.0.1;user id=root;password=234sbn;database=sharding-order";
DataTable dt = new DataTable();
using (var conn = new MySqlConnection(connectionString))
{
try
{
conn.Open();
Console.WriteLine("已成功连接到 MySQL 数据库!");
// 这里可以编写其他操作数据库的代码
string sqlStr = "select * from images";
MySqlDataAdapter da = new MySqlDataAdapter(sqlStr, conn);
da.Fill(dt);
foreach (DataRow item in dt.Rows)
{
string name = item["name"].ToString();
byte[] myData = (byte[])item["data"];
Console.WriteLine($"name={name},byte[0]={myData[0]}");
FileStream F = new FileStream($"C:/Users/zhour/Documents/mypicture{name}.png",
FileMode.OpenOrCreate, FileAccess.Write);
for (int j = 0; j < myData.Length; j++)
{
F.WriteByte(myData[j]);
}
F.Close();
}
int i = 1;
}
catch (Exception ex)
{
Console.WriteLine($"无法连接到 MySQL 数据库:{ex.Message}");
}
finally
{
conn.Close();
}
}
}
}
images表: