从数据库保存Blob文件存储到本地,via C#

这段C#代码演示了如何连接到MySQL数据库,查询包含Blob类型srcfile的t_calpuf_conf表,然后将查询到的文件保存到本地指定目录。通过建立数据库连接,执行SQL查询,读取字节数据并创建二进制写入器完成文件保存。
public static void saveSrc(string curDate)
       {
           MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();

           string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";

           conn.ConnectionString = connStr;

           try
           {
               conn.Open();
           }

           catch
           {
               MessageBox.Show("Database Connection Error");
               return;
           }


           MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
           cmd.Connection = conn;

           cmd.CommandText = "select srcfile from t_calpuf_conf where identifier=\""+identifier+"\"";

           System.Data.Common.DbDataReader reader = cmd.ExecuteReader();

           byte[] buffer = null;

           if (reader.HasRows)
           {
              
               reader.Read();
               long len = reader.GetBytes(0, 0, null, 0, 0);//0是 因为只选出一个字段  第一个0 
               buffer = new byte[len];

               // 字节数
               len = reader.GetBytes(0, 0, buffer, 0, (int)len);

               // 先得创建保存文件的目录

               System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(srcDir + "\\" + identifier);
               di.Create();

               // 再保存

               string savePath = srcDir + "\\"+identifier+"\\src" + curDate + ".src";
               BinaryWriter bw = new BinaryWriter(File.Open(savePath, FileMode.OpenOrCreate));
               bw.Write(buffer);
               bw.Close();  
           }

           cmd.Dispose();
           conn.Close();   
       }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值