用文件流的方式将图片插入SQL Server中 private void Form1_Load(object sender, EventArgs e) { FileStream fs = new FileStream(@"C:/e06d3510ebfde555cb80c4de.jpg", FileMode.Open); int iLength = int.Parse(fs.Length.ToString());//获取当前文件的长度 Byte[] fileByte = new Byte[iLength];//创建一个byte[]的数组,用来保存文件的内容 fs.Read(fileByte, 0, iLength);//通过Read方法,把文件的内容读取到byte[]数组中。 fs.Dispose(); SqlConnection conn = new SqlConnection(@"server=localhost;Integrated Security=SSPI;Initial Catalog=QQ"); //插入数据库 string strSql = "Insert Into tbl_Image (img) Values(@img)"; SqlCommand cmd = new SqlCommand(strSql, conn); cmd.Parameters.Add("@img", SqlDbType.Image, iLength).Value = fileByte; //通过赋值保存的图片的参数的值,为SqlDbType.Binary conn.Open(); //打开连接 cmd.ExecuteNonQuery(); //执行命令 conn.Close(); } 将刚添加进的图片取出并显示在一个图片控件中 private void button1_Click(object sender, EventArgs e) { Byte[] fileContent; using (SqlConnection conn = new SqlConnection(@"server=localhost;Integrated Security=SSPI;Initial Catalog=QQ")) { string strSql = "select img from tbl_Image"; SqlCommand cmd = new SqlCommand(strSql, conn); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); //以上步骤完成一般的SqlCommand的命令的执行, //返回了一个SqlDataReader把图片的内容赋值到一个byte[]数组上。 if (dr.Read()) { fileContent = (Byte[])dr["img"]; } else { fileContent = new Byte[0]; } dr.Close(); } MemoryStream ms = new MemoryStream(fileContent, 0, fileContent.Length); this.pbShowImage.Image = Image.FromStream(ms); //关闭内存流 ms.Close(); }