Posted Monday, February 13, 2006 10:19 AM
|
|
|
|
The following example demontrates how to store and retrieve Matrix objects efficiently in a SQL server databases.
In this example we assume that there is a table with just two fields, an integer field named [ID] and a field defined as image named [Matrix]. The SQL scipt generating this table will be:
CREATE TABLE [MATRIXTABLE] (
[ID] [int] NOT NULL ,
[Matrix] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Below we define two very simple functions that can write and read Matrix objects in the above table.
private void SaveMatrix(int ID, Matrix matrix)
{
// Open the SQL connection
SqlConnection cnn = new SqlConnection("Server=(local);Database=BLUEBIT;User ID=Trifon;Password=xxx");
cnn.Open();
// Create a parametrized sql command
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = "INSERT INTO MATRIXTABLE (ID, MATRIX) VALUES (@ID, @MATRIX )";
// Setting values for the parameters
cmd.Parameters.Add("@ID", ID);
cmd.Parameters.Add("@MATRIX", matrix.Data);
//Execute the command to insert matrix into database table
cmd.ExecuteNonQuery();
}
private Matrix LoadMatrix(int ID)
{
// Open the SQL connection
SqlConnection cnn = new SqlConnection("Server=(local);Database=BLUEBIT;User ID=Trifon;Password=xxx");
cnn.Open();
// Create a SELECT command
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = "SELECT MATRIX FROM MATRIXTABLE WHERE ID=@ID";
cmd.Parameters.Add("@ID", ID);
// Define an reader
SqlDataReader reader = cmd.ExecuteReader();
// read the Matrix object
if(reader.Read())
{
Matrix matrix = new Matrix();
// cast the value as a byte array
matrix.Data = (Byte[]) reader.GetValue(0);
return matrix;
}
else
{
// record does not exist - return null
return null;
}
}
And finally the following lines can test the above:
[STAThread]
static void Main()
{
Matrix A = new Matrix(10,10);
A.FillRandom();
Console.WriteLine(A);
SaveMatrix(1, A);
Matrix B = LoadMatrix(1);
Console.WriteLine(B);
}
The Matrix.Data property is used above to access the raw data stored in the Matrix object.
Trifon Triantafillidis | Lead Developer |
|
|
|
|
|