(转载)如何将图片存进数据库

  //本实例主要介绍如何将图片存入数据库。将图片存入数据库,首先要在数据库中建立一张表,将存储图片的字段类型设为Image类型,用FileStream类、BinaryReader把图片读成字节的形式,赋给一个字节数组,然后用ADO.SqlCommand对象的ExecuteNonQuery()方法来把数据保存到数据库中。主要代码如下:

    openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";

    if(openFileDialog1.ShowDialog()==DialogResult.OK)

    {
     try
     {
      string fullpath =openFileDialog1.FileName;//文件路径

      FileStream fs = new FileStream(fullpath, FileMode.Open);

      byte[] imagebytes =new byte[fs.Length];

      BinaryReader br = new BinaryReader(fs);

      imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));

      //打开数所

      SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=zh");

      con.Open();

      SqlCommand com = new SqlCommand("insert into Image values(@pubimga)",con);
      SqlParameter para =com.Parameters .Add("@pubimga",SqlDbType.Image,16);
      para.Value =imagebytes;

      com.ExecuteNonQuery();

      con.Close();
     }
     catch(Exception ex)
     {
      MessageBox.Show(ex.Message );
     }
    }

posted @ 2008-11-01 10:10  冷风醉饮  阅读(1417)  评论(0)    收藏  举报