6

多次元バイト配列を SQL Server データベースに保存したいと考えています。

画像変換であるバイト配列をデータベースに保存する方法を知っています。そのために私が使用したデータ型はimage. byte [,] tempしかし今、x、y値を持つ2つの次元を持つ多次元バイト配列である別のバイト配列を格納したいと考えています。

インターネットで検索したところ、フォーマットを使用していると言われていVARBINARYます。知りたいのは、多次元配列をVARBINARYデータ型データ列に保存すると、値が変更されるかどうかだけです。データを再び多次元配列として受け取ることは可能ですか?

4

2 に答える 2

7

はい、変更されていない多次元配列を取り戻すことができます。

どうすればできますか?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
            }
        }
    }
}
于 2012-07-04T18:59:28.577 に答える
2

私が知っているように、Microsoft SQL Server には多次元配列を格納するための適切なデータ型がありません。ただし、配列構造に関する情報を保存する方法はたくさんあります。それらのいくつか:

  1. BINARY (固定長) データ型の列をいくつか作成し、多次元配列の各行を適切な列に作成します。この場合、配列内の行数は一定であることが期待されます。

  2. 配列全体を 1 次元配列として VARBINARY (可変長) データ型の 1 つの列に格納し、多次元配列の各行の要素数を INT データ型の別の列に格納します。この場合、各行の要素数は同じであることが期待されます (ぎざぎざの C# 配列ではありません)。配列を読み取るとき、この長さで要素を多次元配列の別々の行に分割できます。

于 2012-07-04T19:17:08.937 に答える