C# · 12月 28, 2021

C#操作数据库中存取图片文件的方法

本文实例讲述了C#操作数据库中存取图片文件的方法。分享给大家供大家参考。具体如下:

private string sqlconnstr = “Data Source=.;Database=db_test;User id=sa;PWD=123456″;/*功能:把一种图片插入到数据库中 *返回值:无 */void InsertImageToDB(){ //将需要存储的图片读取为数据流 FileStream fs = new FileStream(@”D:/Bear.jpg”,FileMode.Open,FileAccess.Read); Byte[] byte_fs = new byte[fs.Length]; fs.Read(byte_fs,Convert.ToInt32(fs.Length)); fs.Close(); //建立数据库连接 sqlConnection conn = new sqlConnection(sqlconnstr); conn.open(); sqlCommand cmd = new sqlCommand(); cmd.Connection = conn; cmd.CommandText = “insert into tb_test(image_id,image_file) values(@image_id,@image_file)”; sqlParameter[] param = new sqlParameter[2]; param[0] = new sqlParameter(“@image_id”,sqlDbType.Int); param[0].Value = 1; param[1] = new sqlParameter(“@image_file”,sqlDbType.Image); param[1].Value = byte_fs; for (int index = 0; index < 2; index++) { cmd.Parameters.Add(param[i]); } //执行sql语句 cmd.ExecuteNonQuery(); conn.Close();}/*功能:从数据库中读取图像文件,并显示在Picture@R_343_2419@控件中 *返回值:无 */void GetImageFromDB(){ byte[] Data = new byte[0]; //建立数据库连接 sqlConnection conn = new sqlConnection(sqlconnstr); conn.open(); sqlCommand cmd = new sqlCommand(); cmd.Connection = conn; cmd.CommandText = “select * from tb_parent”; sqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); Data = (byte[])sdr[“parent_image”];//读取第一个图片的位流 MemoryStream mystream = new MemoryStream(Data); //用指定的数据流来创建一个image图片 System.Drawing.Image picbImage = System.Drawing.Image.FromStream(mystream,true); mystream.Close(); picture@R_343_2419@1.Image = picbImage; conn.Close();}

希望本文所述对大家的C#程序设计有所帮助。