將圖片以二進制形式存入數據庫時,首先要在數據庫中創建一張表,將存儲圖片的字段類型設爲Image類型,用FileStream類、BinaryReader把圖片讀成字節的形式,賦給一個字節數組,而後用ADO.SqlCommand對象的ExecuteNonQuery()方法來把數據保存到數據庫中。主要代碼以下:數據庫
1 private void button1_Clickobject sender, EventArgs e) 2 3 { 4 5 openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP"; 6 7 if(openFileDialog1.ShowDialog()==DialogResult.OK) 8 9 { 10 11 string fullpath =openFileDialog1.FileName;//文件路徑 12 13 FileStream fs = new FileStream(fullpath, FileMode.Open); 14 15 byte[] imagebytes =new byte[fs.Length]; 16 17 BinaryReader br = new BinaryReader(fs); 18 19 imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length)); 20 21 //數據庫鏈接 22 SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05"); 23 24 con.Open(); 25 26 SqlCommand com = new SqlCommand("insert into tb_08 values(@ImageList)",con); 27 28 com.Parameters.Add("ImageList", SqlDbType.Image); 29 30 com.Parameters["ImageList"].Value = imagebytes; 31 32 com.ExecuteNonQuery(); 33 34 con.Close(); 35 36 } 37 38 }