c# 将图片插入数据库

来源:互联网 发布:迷糊系统 相似矩阵 编辑:程序博客网 时间:2024/06/06 20:23

 

  public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            if (string.IsNullOrEmpty(this.pictureBox1.ImageLocation))

            {

                MessageBox.Show("请选择要插入的图片!");

                return;

            }

 

            using (SqlConnection cn = new SqlConnection("Server=.;UID=sa;Pwd=sa;Database=cspro"))

            {

                using (SqlCommand cmd = new SqlCommand("INSERT INTO image_table(pic) VALUES (@pic)", cn))

                {

                    cmd.Parameters.Add("@pic", SqlDbType.Image).Value = File.ReadAllBytes(this.pictureBox1.ImageLocation);

                    cn.Open();

                    cmd.ExecuteNonQuery();

                    cn.Close();

                    MessageBox.Show("图片插入成功!");

                }

            }

        }

 

        private void button3_Click(object sender, EventArgs e)

        {

            using (OpenFileDialog ofd = new OpenFileDialog())

            {

                ofd.Title = "请选择要插入的图片";

                ofd.Filter = "Gif图片|*.gif|Jpg图片|*.jpg|BMP图片|*.bmp";

                ofd.CheckFileExists = true;

                ofd.CheckPathExists = true;

                ofd.Multiselect = false;

                if (ofd.ShowDialog(this) == DialogResult.OK)

                {

                    this.pictureBox1.ImageLocation = ofd.FileName;

                }

                else

                {

                    MessageBox.Show("你没有选择图片");

                }

            }

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            //随机显示一张图片

            using (SqlConnection cn = new SqlConnection("Server=.;UID=sa;Pwd=sa;Database=cspro"))

            {

                using (SqlCommand cmd = new SqlCommand("SELECT pic FROM image_table ORDER BY RAND()", cn))

                {

                    cn.Open();

                    this.pictureBox1.Image = Image.FromStream(new MemoryStream((byte[])cmd.ExecuteScalar(), false));

                    cn.Close();

                }

            }

        }

    }

如图

 

BinDemo

原创粉丝点击