保存和检索图像从mysql数据库

本文关键字:mysql 数据库 图像 检索 保存 | 更新日期: 2023-09-27 18:08:56

对于保存图像,我尝试下面的代码。

MySqlConnection mycon = new MySqlConnection(string.Format("Server=127.0.0.1;Port=3306;Database=test;Uid=root;Pwd=123456;"));
mycon.Open()
FileStream  fs = new FileStream("b.jpg", FileMode.Open, FileAccess.Read);
int sizee = (int)fs.Length;
byte[] rawData = new byte[sizee+1];
fs.Read(rawData, 0, sizee);
fs.Close();
new MySqlCommand(string.Format("INSERT INTO image VALUES(NULL,'{0}',{1})", rawData, sizee), mycon).ExecuteNonQuery();

这段代码工作正常,插入数据成功。但是当我试图检索数据时,它抛出一个异常没有找到适合完成此操作的成像组件

这是用来检索数据的代码。

MySqlConnection mycon = new MySqlConnection(string.Format("Server=127.0.0.1;Port=3306;Database=test;Uid=root;Pwd=123456;"));
        mycon.Open();
        MySqlCommand mycom = new MySqlCommand("Select * from image", mycon);
       MySqlDataReader myData = mycom.ExecuteReader();
       myData.Read();
       int filesize = myData.GetInt32(myData.GetOrdinal("size"));
       byte[] mydatya=new byte[filesize];
       myData.GetBytes(myData.GetOrdinal("myImage"), 0, mydatya, 0, filesize);
       var bitmapImage = new BitmapImage();
       bitmapImage.BeginInit();
       bitmapImage.StreamSource = new MemoryStream(mydatya);
       bitmapImage.EndInit();

保存和检索图像从mysql数据库

通常认为只在数据库中放置对文件的引用并将文件物理地保存在文件夹中是更好的做法。