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

时间:2011-09-15 17:39:39

标签: c# .net mysql

对于保存图片,我试试这段代码。

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();

1 个答案:

答案 0 :(得分:2)

通常认为更好的做法是仅将对文件的引用放在数据库中,并将文件保存在文件夹中。

相关问题