C#操作Sql Server 2005的Image字段

前段遇到了使用Sql server 2005存储图片的问题,现已解决。将程序代码附上以备查看。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace TestPhotoSaveAndQuery
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static string conncetionString = @"data source=.;database=Test;uid=sa;pwd=sa";
        public static SqlConnection conn = new SqlConnection(conncetionString);

        private void button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("insert into UserPhoto values(2,@pic)", conn);
            byte[] photo;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                photo = new byte[fs.Length];
                fs.Read(photo, 0, photo.Length);
                fs.Close();

                SqlParameter parameter = new SqlParameter("@pic", SqlDbType.Image);
                parameter.Value = photo;
                cmd.Parameters.Add(parameter);
                conn.Open();
                int result = cmd.ExecuteNonQuery();
                conn.Close();
                if (result == 1)
                {
                    MessageBox.Show("插入数据成功!");
                }
                else
                {
                    MessageBox.Show("插入数据失败!");
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("select * from UserPhoto where ID=2", conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            byte[] photo = (byte[])ds.Tables[0].Rows[0]["PicImages"];
            if (photo.Length > 0)
            {

      //存图片法
                //string urlImage = Environment.CurrentDirectory + "\\1.jpg";
                //FileStream fs = new FileStream(urlImage, FileMode.OpenOrCreate, FileAccess.Write);
                //MemoryStream ms=new MemoryStream(
                //BinaryWriter bw = new BinaryWriter(fs);
                //bw.BaseStream.Write(photo, 0, photo.Length);
                //bw.Flush();
                //bw.Close();
                //fs.Close();
                //pictureBox1.ImageLocation = urlImage;

      //直接使用数据流法
                using (MemoryStream ms = new MemoryStream(photo, false))
                {
                    pictureBox1.Image = Image.FromStream(ms);
                }
            }
        }
    }
}

posted @ 2012-08-26 12:28  飞絮风翔  阅读(148)  评论(0编辑  收藏  举报