从C#将byte []保存到SQL Server数据库中

Yus*_*tme 45 c# sql-server bytearray

如何将byte []数组保存到SQL Server数据库中?此byte []包含HashAlgorithm值.

需要再次使用该数据以供以后使用.因此,转换它而不是将其恢复到原始状态,这不是我想要的.

提前致谢!

mar*_*c_s 68

你应该能够写出这样的东西:

string queryStmt = "INSERT INTO dbo.YourTable(Content) VALUES(@Content)";

using(SqlConnection _con = new SqlConnection(--your-connection-string-here--))
using(SqlCommand _cmd = new SqlCommand(queryStmt, _con))
{
   SqlParameter param = _cmd.Parameters.Add("@Content", SqlDbType.VarBinary);
   param.Value = YourByteArrayVariableHere;

   _con.Open();
   _cmd.ExecuteNonQuery();
   _con.Close();
}
Run Code Online (Sandbox Code Playgroud)

使用Linq-to-SQL,你会写这样的东西:

using(YourDataContextHere ctx = new YourDataContextHere())
{
   SomeClassOfYours item = new SomeClassOfYours();

   item.ByteContent = (your byte content here);

   ctx.SomeClassOfYourses.InsertOnSubmit(item);
   ctx.SubmitChanges();
}
Run Code Online (Sandbox Code Playgroud)

这会将您的SQL Server表中的类型byte[]列作为字节流插入,您可以稍后再读回1:1.ContentVARBINARY

  • 好答案.但是,根据该值为散列的语句,它可能具有恒定长度.如果是这样,请考虑使用具有该长度的二进制而不是varbinary. (2认同)
  • @Sean Reilly:是的 - 但是不同的哈希算法也产生不同的长度哈希值,因此您可能希望使用具有合适最大长度的VARBINARY来容纳所有变量 (2认同)
  • @marc_s也是如此 - 但是很可能所有行都是相同的哈希算法.如果(并且仅当)是这种情况,我会坚持我的建议,即使用常量长度二进制而不是varbinary. (2认同)

ani*_*vas 6

使用 VARBINARY