ASP.NET如何存取 SQLServer数据库图片(三)

开发者在线 Builder.com.cn 更新时间:2007-08-31作者:中国IT实验室 来源:中国IT实验室

本文关键词: 图片 数据库 sqlserver ASP.NET

      /// <summary>
   /// 应用程序的主入口点。
   /// </summary>
   [STAThread]
   static void Main()
   {
  Application.Run(new Form1());
   }
  
   private void button1_Click(object sender, System.EventArgs e)
 {
  openFileDialog1.ShowDialog ();
  
  if (openFileDialog1.FileName.Trim()!="")
  {
   FileInfo fi = new FileInfo(openFileDialog1.FileName);

   string imgtitle=openFileDialog1.FileName;
   int imgdatalen=(int)fi.Length;
   byte[] imgdata = new byte[imgdatalen];
  
   Stream imgdatastream=fi.OpenRead();
   int n=imgdatastream.Read(imgdata,0,imgdatalen);


   if( conn.State == ConnectionState.Open)
    conn.Close();
   ConnectionString ="Integrated Security=SSPI;" "Initial Catalog=mydb;" "Data  Source=localhost;";
   conn.ConnectionString = ConnectionString;


 try
 {
  string mySelectQuery = "INSERT INTO ImageStore(imgtitle,imgdata) VALUES (@imgtitle, @imgdata )";
  //string mySelectQuery="UPDATE ImageStore set imgtitle=@imgtitle,imgdata=@imgdata" ;
  SqlCommand myCommand = new SqlCommand(mySelectQuery, conn);

  SqlParameter paramTitle = new SqlParameter("@imgtitle", SqlDbType.VarChar,50 );
  paramTitle.Value = imgtitle;
  myCommand.Parameters.Add( paramTitle);

  SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
  paramData.Value = imgdata;
  myCommand.Parameters.Add( paramData );

  conn.Open();
  int numRowsAffected = myCommand.ExecuteNonQuery();
  conn.Close();
 }
 catch(Exception err)
 {
  MessageBox.Show("您输入名称可能在数据库中已存在或输入为空,请检查!" err.ToString() );
 }
 finally
 {}
}

}

 private  void Form1_Load(object sender, System.EventArgs e)
 

 private void button2_Click(object sender, System.EventArgs e)
 {
  //打开数据库连接
  if( conn.State == ConnectionState.Open)
   conn.Close();
  ConnectionString ="Integrated Security=SSPI;" "Initial Catalog=mydb;" "Data Source=localhost;";
  conn.ConnectionString = ConnectionString;

  // 创建数据适配器
  string sql="SELECT * FROM ImageStore" ;
  SqlCommand command = new SqlCommand(sql, conn);
 
  try
  
  catch(Exception newerr)
  {
   MessageBox.Show(" 不能打开数据联接!") ;
  }
  finally
  {}

  SqlDataReader dr = command.ExecuteReader();
  if(dr.Read())
  {
   FileInfo fi = new FileInfo("temp");
   FileStream myStream=fi.Open(FileMode.Create);
   byte[] mydata=((byte[])dr["imgdata"]);
   //label2.Text="您现在看到的是:" dr["imgtitle"].ToString();
   foreach(byte a in mydata)
   {
    myStream.WriteByte(a);
   }
  myStream.Close();
  Image myImage=Image.FromFile("temp") ;
  pic1.Image=myImage;
  pic1.Refresh();
  dr.Close ();

 }
 else
 {
  MessageBox.Show("没有成功读入数据!") ;
 
 }

 conn.Close();

}

}
} 查看本文来源

用户评论

  • 用户名
  • 评论内容