65.9K
CodeProject 正在变化。 阅读更多。
Home

将图像加载/卸载到/从数据库表中

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.88/5 (25投票s)

2005年1月17日

viewsIcon

221881

downloadIcon

3510

解释如何将 BLOB 数据加载到数据库表中以及如何从数据库表中获取它。

Sample Image - imageStorage.jpg

引言

我们经常需要将大型二进制对象(BLOB)存储到数据库表中,然后从那里获取它们。现在我将解释最简单的方法来做到这一点。

准备数据库

运行 SQL Server Enterprise Manager 并创建一个新的数据库,命名为 'Test'。创建一个新的表并命名为 Images

CREATE TABLE Images ([stream] [image] NULL)

这些就足够了。

将图像存储到数据库表中

...
byte[] content = ReadBitmap2ByteArray(fileName);
StoreBlob2DataBase(content);
...
protected static byte[] ReadBitmap2ByteArray(string fileName)
{
  using(Bitmap image = new Bitmap(fileName))
  {
    MemoryStream stream = new MemoryStream();
    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
    return stream.ToArray();
  }
}

protected static void StoreBlob2DataBase(byte[] content)
{
   SqlConnection con = Connection;
   con.Open();
   try
   {
     // insert new entry into table
     SqlCommand insert = new SqlCommand(
     "insert into Images ([stream]) values (@image)",con);
     SqlParameter imageParameter = 
     insert.Parameters.Add("@image", SqlDbType.Binary);
     imageParameter.Value = content;
     imageParameter.Size  = content.Length;
     insert.ExecuteNonQuery();
   }
   finally
   {
      con.Close();
   }
}

为 OLEDB 提供程序存储图像

我们中的一些人使用 OLEDB 提供程序与 SQL Server 通信。在这种情况下,您应该使用以下代码将图像存储到数据库中。请注意在 SQL 查询中使用 '?' 而不是 '@image'。

protected static void StoreBlob2DataBaseOleDb(byte[] content)
{
   try
   {
      using(OleDbConnection con = Connection)
      {
         con.Open();

         // insert new entry into table
         using(OleDbCommand insert = new OleDbCommand(
             "insert into Images ([stream]) values (?)",con))
         {
            OleDbParameter imageParameter = 
            insert.Parameters.Add("@image", OleDbType.Binary);
            imageParameter.Value = content;
            imageParameter.Size  = content.Length;
            insert.ExecuteNonQuery();
         }
      }
   }
   catch(Exception ex)
   {
      // some exception processing
   }
}

从数据库表中获取图像并显示它

 // get image
 DataRowView drv = (DataRowView) _cm.Current;
 byte[] content = (byte[])drv["stream"];
 MemoryStream stream = new MemoryStream(content);
 Bitmap image = new Bitmap(stream);
 
 ShowImageForm f = new ShowImageForm();
 f._viewer.Image = image;
 f.ShowDialog(this);

结论

您可以使用这种技术处理任何类型的二进制数据,而无需使用存储过程。祝你好运。

© . All rights reserved.