C# 向SQL数据库中存储图片的方法

向数据库中存储图片的方法有两种:

1.将图片转换成二进制的形式存储到数据库

2.将图片的路径存储到数据库中,用时通过路径找到图片

下面分别介绍这两种方法

1.将图片转换成二进制形式存储

首先,在sql数据库中建立一个表,有两个字段:ID、Image,其中ID为主键,Image的存储类型为Image类型。

单击button1按钮,实现图片存储:

private void button1_Click(object sender, EventArgs e)
        {
            
            openFileDialog1.Filter="*.jpg|*.JPG";//设置弹出对话框选择图片
            openFileDialog1.ShowDialog();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = openFileDialog1.FileName;
                using (FileStream filestream = new FileStream(path, FileMode.Open))
                {
                    Byte[] imageByte = new byte[filestream.Length];
                    filestream.Read(imageByte,0,imageByte.Length);//将图片数据读入比特数组存储
                    string connectionstring = "Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI";
                    SqlConnection sqlcon = new SqlConnection(connectionstring);
                    sqlcon.Open();
                    SqlCommand sqlcom = new SqlCommand("insert into Image(ID,Image) values (1,@ImageList)",sqlcon);//此处设置一个占位符ImageList,含义将在以下定义
                    sqlcom.Parameters.Add("ImageList",SqlDbType.Image);
                    sqlcom.Parameters["ImageList"].Value = imageByte;
                    sqlcom.ExecuteNonQuery();
                    sqlcon.Close();
                }
            }
            
        }

单击button2按钮,实现图片的提取:

private void button2_Click(object sender, EventArgs e)
        {
            string connectionstring = "Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI";
            SqlConnection sqlcon = new SqlConnection(connectionstring);
            sqlcon.Open();
            byte[] imagebytes;
            SqlCommand sqlcom = new SqlCommand("select Image from Image where ID=1",sqlcon);//查询到要提取的图片
            SqlDataReader dr = sqlcom.ExecuteReader();
            if (dr.Read())
            {
                imagebytes = (byte[])dr["Image"];
                MemoryStream ms = new MemoryStream(imagebytes);//创建图片数据流
                Bitmap bmap = new Bitmap(ms);//获取图片
                ms.Close();
                pictureBox1.Image = bmap;
            }
        }

2.路径存取法

这个简单,只要把图片的路径转换成字符串,存储到数据库中,使用时将字符串提取出来,将其赋值给pictureBox的URL或ImageLocation属性即可。

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值