问题描述
我要救一个多维字节数组到一个SQL Server数据库。
I want to save a multidimensional byte array to a SQL Server database.
我知道如何保存一个字节数组这是一个图像转换到数据库。对于我所使用的数据类型是图片
。但现在我想要存储的另一个字节数组是多维的字节数组字节[,]温度
,其中有两个维度为x,y值。
I know how to save a byte array which is a image conversion to a database. For that the data type I used is image
. But now I want to store another byte array which is multidimensional byte array byte [,] temp
, which has two dimensions with x,y values.
我搜索的互联网和这里,据说使用 VARBINARY
格式。所有我想知道的是,如果我救我的多维数组在 VARBINARY
数据类型的数据列,将值将被改变?是否有可能再次接收数据传回的多维数组?
I searched on internet and here, it is said that using VARBINARY
format. All I want to know is if I save my multidimensional array in a VARBINARY
datatype data column, will the values will be altered? Is it possible to receive the data back as multidimensional array again?
推荐答案
是的,你就能拿回你的多维数组不变。
Yes, you will be able to get back your multi-dimensional array unaltered.
你怎么能这样做呢?是在SQL Server中的varbinary(最大值)场并保存到它的序列化多维字节数组。 ,为了让您的阵列回来,obviusly,你需要反序列化将存储在数据库中有哪些
How can you do it? Using a Varbinary(max) field in Sql Server and saving into it the serialized multidimensional byte array. In order to get your array back, obviusly, you need to deserialize what you stored in the database.
下面是如何做到这一点的例子:
Here is an example of how to do it:
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
}
}
}
}
这篇关于保存多维字节数组到SQL Server数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!