C#中如何存取sql server中的图片

private void button1_Click(object sender, System.EventArgs e)//存
  {
   Stream ms;
   byte[] picbyte;
   //ofdSelectPic.ShowDialog();
   if (ofdSelectPic.ShowDialog()==DialogResult.OK)
   {
    if ((ms=ofdSelectPic.OpenFile())!=null)
    {
     //MessageBox.Show("ok");
     picbyte=new byte[ms.Length];
     ms.Position=0;
     ms.Read(picbyte,0,Convert.ToInt32(ms.Length));
     
     //MessageBox.Show("读取完毕!");

     //连接数据库
     

     SqlCommand cmd=new SqlCommand("UpdateImage",conn);
     cmd.CommandType=CommandType.StoredProcedure;

     cmd.Parameters.Add("@UpdateImage",SqlDbType.Image);
     cmd.Parameters["@UpdateImage"].Value=picbyte;

     conn.Open();
     cmd.ExecuteNonQuery();
     conn.Close();

     ms.Close();
    }
   }


  }






//取
 private void button2_Click(object sender, System.EventArgs e)
  {
   

   string strSql="select FImage from test order by newid()";

   SqlCommand cmd=new SqlCommand(strSql,conn);

   conn.Open();
   SqlDataReader reader=cmd.ExecuteReader();
   reader.Read();

   MemoryStream ms=new MemoryStream((byte[])reader["FImage"]);


   Image image=Image.FromStream(ms,true);

   reader.Close();
   conn.Close();

   ptbShow.Image=image;


  }

posted @ 2006-04-10 20:07  阿东工作室  阅读(292)  评论(0编辑  收藏  举报