当前位置:   article > 正文

C#存储文件到数据库中 字段类型为image_c# 写 image 字段

c# 写 image 字段

方法一:文件转为字节数组再转为16进制字符串 传统sql语句拼接添加

  1. string connString = "server=.;database=student;user id=sa;password=123456";
  2. SqlConnection connection = new SqlConnection (connString);
  3. //savePath为文件路径
  4. FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read);
  5. Byte[] btye2 = new byte[fs.Length];
  6. fs.Read(btye2, 0, Convert.ToInt32(fs.Length));
  7. fs.Close();
  8. //字节数组转字符串(十六进制)
  9. string Instruction = "";
  10. StringBuilder builder = new StringBuilder();
  11. for (int i = 0; i < btye2.Length; i++)
  12. {
  13. builder.Append(string.Format("{0:X2}", btye2[i]));
  14. }
  15. Instruction = builder.ToString().Trim();
  16. //注意,此时还没有真正连接,我们需要调用open()方法,打开连接
  17. connection.Open();
  18. string sql = "update Maintenance set Instruction=0x" + Instruction;//加上0x表示为16进制 注意不要加单引号
  19. SqlCommand command=new SqlCommand(sql,connection);
  20. int result= command.ExecuteNonQuery ()

方法二:以二进制字节流存储到数据库 SqlCommand.Parameters.Add 添加参数并赋值

  1. string connString = "server=.;database=student;user id=sa;password=123456";
  2. SqlConnection connection = new SqlConnection (connString);
  3. //savePath为文件路径
  4. FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read);
  5. //创建二进制流对象
  6. BinaryReader BReader = new BinaryReader(fs);
  7. byte[] byteImage = BReader.ReadBytes((int)fs.Length); //获取到字节流
  8. SqlCommand sqlCmd = new SqlCommand("Insert into tb_Image(photo)values(@photo)", connection );
  9. //添加参数并赋值
  10. sqlCmd.Parameters.Add("@photo", SqlDbType.Image).Value = byteImage;
  11. connection.Open();
  12. connection.ExecuteNonQuery();
  13. connection.Close();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/1001682
推荐阅读
相关标签
  

闽ICP备14008679号