从 C# 将 byte[] 保存到 SQL Server 数据库中 [英] Save byte[] into a SQL Server database from C#

查看:55
本文介绍了从 C# 将 byte[] 保存到 SQL Server 数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 byte[] 数组保存到 SQL Server 数据库中?这个字节[]包含一个HashAlgorithm值.

How can I save a byte[] array into a SQL Server database? This byte[] contains a HashAlgorithm value.

再次需要数据以备后用.所以转换它而不是让它恢复到原来的状态,不是我想要的.

The data is needed again for later use. So converting it and NOT getting it back in its original state, is not what I want.

提前致谢!

推荐答案

你应该可以这样写:

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 Linq-to-SQL, you'd write something like this:

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再读一遍.

That will insert your byte[] into a column Content of type VARBINARY in your SQL Server table as a byte stream, which you can read back 1:1 again later on.

这篇关于从 C# 将 byte[] 保存到 SQL Server 数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆