繁体   English   中英

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

[英]Saving multidimensional byte array to SQL Server database

我想将多维字节数组保存到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
            }
        }
    }
}

据我所知,Microsoft SQL Server中没有适当的数据类型来存储多维数组。 但是,有许多方法可以保存有关数组结构的信息。 他们中的几个:

  1. 创建几列BINARY(固定长度)数据类型,并将多维数组的每一行创建到适当的列; 在这种情况下,预计数组中的行数是常量;

  2. 将整个数组作为一维数组存储到VARBINARY(可变长度)数据类型的单列中,并在INT数据类型的单独列中存储多维数组中每行的元素数; 在这种情况下,预计每行中元素的数量是相同的(不是锯齿状的C#数组); 在读取数组时,您将能够按此长度将元素拆分为多维数组的单独行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM