C#从mysql数据库中读取图片数据

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表:
在这里插入图片描述

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值