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;
public class Car
public string name;
public int age;
public Car(string name,int age)
public void Up()

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