C#把图片存入到SQL2008数据库中

openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
            SqlConnection con = new SqlConnection(conmmsy);
            con.Open();
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string path = openFileDialog1.FileName;//文件路径                    
                    //创建文件流,path参数是文件路径  
                    FileStream fs = new FileStream(path, FileMode.Open);
                    int streamLength = (int)fs.Length;  //获取文件流的长度。  
                    byte[] image = new byte[streamLength];    //声明字节数组,用于保存图片文件  
                    fs.Read(image, 0, streamLength);    //把图片文件转换成为字节数组保存  
                    fs.Close();
                    //插入Sql语句,@img是Sql语句参数。  
                    string sql = string.Format("insert imagetable values(@img)", image);
                    SqlCommand com = new SqlCommand(sql, con); //con是一个有效的连接对象  
                                                               //为命令对象添加参数,注意参数的类型  
                    com.Parameters.Add(new SqlParameter("img", SqlDbType.Binary, image.Length,
                    ParameterDirection.Input, true, 0, 0, null, DataRowVersion.Default, image));
                    com.ExecuteNonQuery();   //执行  
                    MessageBox.Show("插入成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "插入图片不成功");
            }
            finally
            {
                con.Close();
            }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值