c# - 将多维字节数组保存到 SQL Server 数据库

标签 c# sql sql-server multidimensional-array bytearray

我想将多维字节数组保存到 SQL Server 数据库中。

我知道如何保存一个字节数组,它是一个图像转换到数据库。为此,我使用的数据类型是 image。但现在我想存储另一个字节数组,它是多维字节数组 byte [,] temp,它有两个维度,有 x,y 值。

我在网上和这里搜索了一下,据说是使用VARBINARY格式。我想知道的是,如果我将多维数组保存在 VARBINARY 数据类型的数据列中,这些值是否会被更改?是否可以再次将数据作为多维数组接收回来?

最佳答案

是的,您将能够原封不动地取回您的多维数组。

你怎么做? 在 Sql Server 中使用 Varbinary(max) 字段并将序列化的多维字节数组保存到其中。显然,为了取回数组,您需要反序列化存储在数据库中的内容。

这是一个如何做到这一点的例子:

public void TestSO()
{
    using (SqlConnection conexion = new SqlConnection())
    {
        using (SqlCommand command = new SqlCommand())
        {
            //This is the original multidimensional byte array
            byte[,] byteArray = new byte[2, 2] {{1, 0}, {0,1}};
            ConnectionStringSettings conString = ConfigurationManager.ConnectionStrings["ConnectionString"];
            conexion.ConnectionString = conString.ConnectionString;
            conexion.Open();
            command.Connection = conexion;
            command.CommandType = CommandType.Text;
            command.CommandText = "UPDATE Table SET VarBinaryField = @Content WHERE Id = 73 ";
            command.Parameters.Add(new SqlParameter("@Content", SqlDbType.VarBinary, -1));
            //Serialize the multidimensional byte array to a byte[]
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, byteArray);
            //Set the serialized original array as the parameter value for the query
            command.Parameters["@Content"].Value = ms.ToArray();
            if (command.ExecuteNonQuery() > 0)
            {
                //This method returns the VarBinaryField from the database (what we just saved)
                byte[] content = GetAttachmentContentsById(73);
                //Deserialize Content to a multidimensional array
                MemoryStream ms2 = new MemoryStream(content);
                byte[,] fetchedByteArray = (byte[,])bf.Deserialize(ms2);
                //At this point, fetchedByteArray is exactly the same as the original byte array
            }
        }
    }
}

关于c# - 将多维字节数组保存到 SQL Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11334172/

相关文章:

时间:2019-03-17 标签:c#mysqlselectwithwherecondition

c# - Windows 8.1 应用程序中的事件日志记录

mysql - 对相同类型表的两个相同类型的查询但输出不同

c# - sql 数据库错误 "Must declare the scalar variable"

c# - C# 中的 TimeSpan "pretty time"格式

c# - 将分部 View 转换为 HTML

sql - 在 SELECT 语句中重置 SQL 变量

c# - 从 DataSet 创建 SQL Server 数据库

sql - "JOIN"和 "INNER JOIN"意思一样吗

sql - 从父节点 xml sql server 检索所有子节点