mysql讀寫檔案

來源:互聯網
上載者:User

如何將檔案儲存到資料庫中呢,其實並不是想象中那麼難

主要的思路就是將檔案用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;                    }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.