C#操作數(shù)據(jù)庫中存取圖片文件的方法
更新時間:2015年10月09日 17:06:49 作者:weiren2006
這篇文章主要介紹了C#操作數(shù)據(jù)庫中存取圖片文件的方法,以實例形式分析了C#將圖片存入數(shù)據(jù)庫及從數(shù)據(jù)庫讀取圖片文件的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#操作數(shù)據(jù)庫中存取圖片文件的方法。分享給大家供大家參考。具體如下:
private string sqlconnstr = "Data Source=.;Database=db_test;User id=sa;PWD=123456"; /*功能:把一種圖片插入到數(shù)據(jù)庫中 *返回值:無 */ void InsertImageToDB() { //將需要存儲的圖片讀取為數(shù)據(jù)流 FileStream fs = new FileStream(@"D:/Bear.jpg", FileMode.Open, FileAccess.Read); Byte[] byte_fs = new byte[fs.Length]; fs.Read(byte_fs, 0, Convert.ToInt32(fs.Length)); fs.Close(); //建立數(shù)據(jù)庫連接 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]); } //執(zhí)行SQL語句 cmd.ExecuteNonQuery(); conn.Close(); } /*功能:從數(shù)據(jù)庫中讀取圖像文件,并顯示在PictureBox控件中 *返回值:無 */ void GetImageFromDB() { byte[] Data = new byte[0]; //建立數(shù)據(jù)庫連接 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); //用指定的數(shù)據(jù)流來創(chuàng)建一個image圖片 System.Drawing.Image picbImage = System.Drawing.Image.FromStream(mystream, true); mystream.Close(); picturebox1.Image = picbImage; conn.Close(); }
希望本文所述對大家的C#程序設計有所幫助。
相關(guān)文章
C#簡單查詢SQLite數(shù)據(jù)庫是否存在數(shù)據(jù)的方法
這篇文章主要介紹了C#簡單查詢SQLite數(shù)據(jù)庫是否存在數(shù)據(jù)的方法,涉及C#調(diào)用SQLite組件及針對SQLite數(shù)據(jù)庫基本的連接、查詢、關(guān)閉等使用技巧,需要的朋友可以參考下2016-07-07