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

问题描述 投票:41回答:4

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

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

提前致谢!

c# sql-server bytearray
4个回答
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();
}

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

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

   item.ByteContent = (your byte content here);

   ctx.SomeClassOfYourses.InsertOnSubmit(item);
   ctx.SubmitChanges();
}

这会将你的qazxsw poi插入到你的SQL Server表中qazxsw poi类型的qazxsw poi列中作为字节流,你可以稍后再读回1:1。


6
投票

使用byte[]


2
投票

Varbinary或CHAR - 将值转换为十六进制。我经常使用哈希值,因为它允许我轻松地查看和比较它们(在rintouts上,在开发期间),并且开销很小。


0
投票

使用Dapper,您可以像这样轻松地保存HTML代码:

Content

然后你可以从数据库DECOMPRESS它像这样:

VARBINARY
© www.soinside.com 2019 - 2024. All rights reserved.