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

本文详细介绍了两种方法:一是通过文件操作将文件内容转换为字节数组并拼接成16进制字符串,然后更新数据库;二是使用BinaryReader直接将文件内容作为二进制数据存储到数据库中。
摘要由CSDN通过智能技术生成

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

string connString = "server=.;database=student;user id=sa;password=123456";
SqlConnection connection = new SqlConnection (connString);


//savePath为文件路径
FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read);
Byte[] btye2 = new byte[fs.Length];
fs.Read(btye2, 0, Convert.ToInt32(fs.Length));
fs.Close();
//字节数组转字符串(十六进制)
string Instruction = "";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < btye2.Length; i++)
{
    builder.Append(string.Format("{0:X2}", btye2[i]));
}
Instruction = builder.ToString().Trim();
//注意,此时还没有真正连接,我们需要调用open()方法,打开连接
connection.Open();
string sql = "update  Maintenance set Instruction=0x" + Instruction;//加上0x表示为16进制 注意不要加单引号
SqlCommand command=new SqlCommand(sql,connection);        
int result= command.ExecuteNonQuery ()      

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

string connString = "server=.;database=student;user id=sa;password=123456";
SqlConnection connection = new SqlConnection (connString);


//savePath为文件路径
FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read);
//创建二进制流对象
BinaryReader BReader = new BinaryReader(fs);
byte[] byteImage = BReader.ReadBytes((int)fs.Length); //获取到字节流
   
SqlCommand sqlCmd = new SqlCommand("Insert into tb_Image(photo)values(@photo)", connection );

//添加参数并赋值
sqlCmd.Parameters.Add("@photo", SqlDbType.Image).Value = byteImage;
connection.Open();
connection.ExecuteNonQuery();
connection.Close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值