加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:17:55 所属栏目:百科 来源:网络整理
导读:我想将多维字节数组保存到SQL Server数据库. 我知道如何保存一个字节数组,这是一个图像转换到数据库.为此,我使用的数据类型是图像.但现在我想存储另一个字节数组,它是多维字节数组byte [,] temp,它有两个维度,带有x,y值. 我在互联网上搜索过,据说使用VARBINA
我想将多维字节数组保存到SQL Server数据库.

我知道如何保存一个字节数组,这是一个图像转换到数据库.为此,我使用的数据类型是图像.但现在我想存储另一个字节数组,它是多维字节数组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
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读