方法一:文件转为字节数组再转为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();