【发布时间】:2011-05-02 17:55:23
【问题描述】:
如何将 byte[] 数组保存到 SQL Server 数据库中? 这个 byte[] 包含一个 HashAlgorithm 值。
再次需要数据以供以后使用。所以转换它而不是让它回到原来的状态,不是我想要的。
提前致谢!
【问题讨论】:
标签: c# sql-server bytearray
如何将 byte[] 数组保存到 SQL Server 数据库中? 这个 byte[] 包含一个 HashAlgorithm 值。
再次需要数据以供以后使用。所以转换它而不是让它回到原来的状态,不是我想要的。
提前致谢!
【问题讨论】:
标签: c# sql-server bytearray
你应该可以这样写:
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();
}
这会将您的 byte[] 作为字节流插入到 SQL Server 表中 VARBINARY 类型的列 Content 中,稍后您可以再次以 1:1 的比例读回。
【讨论】:
使用VARBINARY
【讨论】:
Varbinary 或 CHAR - 将值转换为十六进制。我经常使用哈希值这样做,因为它让我可以轻松地查看和比较它们(在 rintouts 中,在开发过程中),而且开销很小。
【讨论】:
使用 Dapper,您可以像这样轻松保存 HTML 代码:
using (var con = DapperConnection.Con)
{
string firstValue = "any text...";
string secondValue = "HTML code maybe ?";
// Convert your string into byte array:
byte[] htmlCode = Encoding.ASCII.GetBytes(secondValue);
// Define your insert query and execute it:
con.Execute($@" INSERT INTO [dbo].[YourTableName]
( [firstColumnName], [secondColumnName] )
VALUES
( {firstValue}, COMPRESS(@HTML) )", new { HTML = htmlCode });
}
然后你可以像这样从数据库中解压它:
SELECT [firstColumnName], CONVERT(varchar(MAX), DECOMPRESS([secondColumnName])) FROM [YourTableName];
【讨论】: