mysql读写文件

如何将文件保存到数据库中呢,其实并不是想象中那么难

主要的思路就是将文件用byte数组保存,在数据库中用(blob   longblob   mediumblob,他们是是一个可以存储二进制文件的容器,可以参考百度百科)三者中的任意格式保存就ok啦!

下面看文件具体如何写入数据库

          //eg .string picname = "E:\\BITMAP\\副本.jpg"
                FileStream fs = new FileStream(picname, FileMode.Open, FileAccess.Read);
                Byte[] imageByte = new byte[fs.Length];
                fs.Read(imageByte, 0, (int)fs.Length);
                //设置命令参数
                MySqlCommand com = new MySqlCommand();
                com.CommandText = "update picture set image=@image"  + ",image_type='" + imagetype.ToString() + "'" + "where pic_id='" + pic_id + "'";
                com.Parameters.Add("@image", MySqlDbType.MediumBlob).Value = imageByte;
                com.Connection = DB_op.g_conn;
                return (1==com.ExecuteNonQuery());

读取文件:

  MySqlDataReader dr = com.ExecuteReader();
                if (dr.Read())  //z这。。。。。
                {
                    byte[] configByte = (byte[])dr[0];
                    ////dr.GetBytes(0, 0, configByte, 0, configByte.Length);
                    ////将文件字节数组加入到缓冲流
                    //MemoryStream configStream = new MemoryStream(configByte);
                    ////StreamWriter sw = new StreamWriter(configStream);
                    //StreamReader reader = new StreamReader(configStream);
                    //byte[] bytes = new byte[configStream.Length];
                    FileStream fs = new FileStream(strsavepath, FileMode.Create);
                    int numBytesRead = 0;
                //    int numBytesToRead = (int)configStream.Length;
                    int numBytesToRead = configByte.Length;
                    while (numBytesToRead > 0)
                    {
                        int n = configStream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue));
                        if (n <= 0)
                        {
                            break;
                        }
                        fs.Write(bytes, numBytesRead, n);
                        numBytesRead += n;
                        numBytesToRead -= n;
                    }
原文地址:https://www.cnblogs.com/jck34/p/2731891.html