Saving and Reading Object to/from a Database


There are many occasions when you want to save data in form of objects. An object is a memory stream, which is hard to write using the normal methods. In this article, I show how you can save objects in a database and read back from the database.

Note: Please Execute tst.sql in MS-SQL

This code shows how to save objects in a database. An object can be easily by using Serializing and ADO.NET. The Serialize method of BinaryFormatter class serializes an object, or graph of connected objects, to the given stream. The Deserialize method of BinaryFormatter deserializes the stream into an object graph.

The MemoryStream class of the .NET framework library which uses memory as a data storage. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.

An stream is an array of bytes and data storage. In this program, I create an object of class Car and read data in a BinaryFormatter object. After that I create a DataSet object and use BinaryFomatter class object and set DataTable's field value to the object.

using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Car
{
public string name;
public int age;
public Car(string name,int age)
{
this.name=name;
this.age=age;
}
public void Up()
{
age++;
}

public class Test
{
public static void Main()
{
Console.Write("name:");
string sname=Console.ReadLine();
Console.Write("age:");
string sage=Console.ReadLine();
Car car=new Car(sname,Int32.Parse(sage));
MemoryStream ms=new MemoryStream();
BinaryFormatter b=new BinaryFormatter();
b.Serialize(ms,car);
SqlConnection con=new SqlConnection "server=localhost;uid=sa;pwd=;database=test");
con.Open();
SqlDataAdapter ad=new SqlDataAdapter("select * from tst",con);
DataSet ds=new DataSet();
ad.Fill(ds,"tblFile");
DataTable dbTable = ds.Tables["tblFile"];
DataRow dbRow = dbTable.NewRow();
// Store data in the row
dbRow["id"] = "kimlee";
dbRow["obj"] = ms.GetBuffer();
dbRow["len"]=ms.Length;
dbTable.Rows.Add(dbRow);
// Update data source
SqlCommandBuilder cb=new SqlCommandBuilder(ad);
ad.Update(ds, "tblFile");
SqlCommand comd=new SqlCommand("select * from tst",con);
SqlDataReader sr=comd.ExecuteReader();
while(sr.Read())
{
byte[] cc=new byte[(int)sr["len"]];
sr.GetBytes(1,0,cc,0,(int)sr["len"]);
MemoryStream mss=new MemoryStream(cc);
Car dcar=(Car)b.Deserialize(mss);
dcar.Up();
Console.Write("name:");
Console.WriteLine(dcar.name) ;
Console.Write("age:");
Console.WriteLine(dcar.age) ;
}
con.Close();
}
}

Up Next
    Ebook Download
    View all
    Learn
    View all