取出数据
SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=yzj;database=_Test"); conn.Open(); SqlCommand cmd = new SqlCommand("select Img from Image", conn); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { MemoryStream buf = new MemoryStream((byte[])reader[i]); Image image = Image.FromStream(buf, true); pictureBox1.Image =new Bitmap(image, 200, 100);//缩放 pictureBox2.Image = image; } }
存入数据
SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=yzj;database=_Test"); conn.Open(); SqlCommand cmd = new SqlCommand("insert into Image values(@i)", conn); byte[] ib = new byte[1000000]; OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "打开"; ofd.Filter = "所有文件|*.*"; //这是设置扩展名。 if (ofd.ShowDialog() == DialogResult.OK) { FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read); fs.Read(ib, 0, 60000); cmd.Parameters.Add("@i", SqlDbType.Image, (int)fs.Length); cmd.Parameters["@i"].Value = ib; cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("保存成功"); }