Chinaunix首页 | 论坛 | 博客
  • 博客访问: 414186
  • 博文数量: 116
  • 博客积分: 7087
  • 博客等级: 少将
  • 技术积分: 1175
  • 用 户 组: 普通用户
  • 注册时间: 2005-02-19 23:32
文章分类

全部博文(116)

文章存档

2012年(1)

2011年(2)

2010年(10)

2009年(21)

2008年(18)

2007年(12)

2006年(21)

2005年(31)

我的朋友

分类:

2005-08-31 09:02:31

如何将blob数据存入或取出数据库?用.net之后,就显得很方便,和很直接

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

-------------------------------------------------------------------------------

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

阅读(782) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~