C# SQL Server数据库图片存取

数据库字段

在这里插入图片描述

界面结构

在这里插入图片描述

C#代码

存入数据库

        string connString = "initial catalog=Picture;Server=(local);user id=molihuan;password=123456";//数据库连接字符串
        private void cun_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
            try{
                if (openFileDialog1.ShowDialog() == DialogResult.OK) {

                    string picturePath = openFileDialog1.FileName; //选择的图片路径
                    SqlConnection connection = new SqlConnection(connString);//创建connection对象
                    string sql = "insert into Images (ID,Data) values ("+textBox2.Text+",@blobdata)";
                    SqlCommand command = new SqlCommand(sql, connection);
                    //创建FileStream对象
                    FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
                    //声明Byte数组
                    Byte[] mybyte = new byte[fs.Length];
                    //读取数据
                    fs.Read(mybyte, 0, mybyte.Length);
                    fs.Close();
                    //转换成二进制数据,并保存到数据库
                    SqlParameter prm = new SqlParameter
                        ("@blobdata", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
                    command.Parameters.Add(prm);
                    //打开数据库连接
                    connection.Open();
                    command.ExecuteNonQuery();//执行代码
                    connection.Close();
                    MessageBox.Show("存入数据库成功");
                }
            }catch (Exception ex){MessageBox.Show(ex.Message);}
        }

读取数据库存储的图片

        private void du_Click(object sender, EventArgs e)
        {
            byte[] imagebytes = null;
            //打开数据库
            SqlConnection con = new SqlConnection(connString);
            con.Open();
            if (textBox1.Text.Equals(""))
            {
                textBox1.Text = "1";
            }
            SqlCommand com = new SqlCommand("select * from Images where ID="+textBox2.Text, con);
            SqlDataReader dr = com.ExecuteReader();
            while (dr.Read())
            {
                imagebytes = (byte[])dr.GetValue(1);
            }
            dr.Close();
            com.Clone();
            con.Close();
            MemoryStream ms = new MemoryStream(imagebytes);
            Bitmap bmpt = new Bitmap(ms);
            pictureBox1.Image = bmpt;
        }

参考文章

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值