且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-07 09:40:40

你应该可以这样写:

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.