Connected V/S Disconnected Architecture In C#

In C#, we work in two different ways with database connectivity. As you know when we create software or website or any other application which is connected to the database we need to make connection to the database to get data. Here you can get data in two different ways.

Either it can be connected architecture where you go and connect to the database and get data or disconnected architecture where you connect to the database first time and get all data in an object and use it if required. You can perform any action like insert, update, and search on this.

You can use two C# objects to achieve this, first one is DataSet and other one is DataReader.

DataSet

DataSet

It is a type of disconnected architecture. Disconnected architecture means, you don’t need to connect always when you want to get data from the database. You can get data from dataset; basically DataSet is a collection of datatables. We can store the database table, view data in the DataSet and can also store the xml value in dataset and get it if required.

To achieve this you need to use DataAdapter which work as a mediator between Database and DataSet.

Example

  1. public DataSet GetEmployeeData()  
  2. {  
  3.     SqlConnection conString = new SqlConnection("myconnection");  
  4.     conString.Open();  
  5.     SqlCommand cmdQuery = new SqlCommand("Select * from Employee", conString);  
  6.     SqlDataAdapter sda = new SqlDataAdapter(cmdQuery);  
  7.     DataSet dsData = new DataSet();  
  8.     sda.Fill(dsData);  
  9.     return dsData;  
  10. }  
DataReader

It is a connected architecture, which means when you require  data from the database you need to connect with database and fetch the data from there. You can use if you need updated data from the database in a faster manner. DataReader is Read/Forward only that means we can only get the data using this but we cannot update or insert the data into the database. It fetches the record one by one.

Example
  1. static void HasRows(SqlConnection connection)  
  2. {  
  3.     using (connection)  
  4.     {  
  5.         SqlCommand command = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);  
  6.         connection.Open();  
  7.         SqlDataReader reader = command.ExecuteReader();  
  8.         if (reader.HasRows)  
  9.         {  
  10.             while (reader.Read())  
  11.             {  
  12.                 Console.WriteLine("{0}\t{1}", reader.GetInt32(0),reader.GetString(1));  
  13.             }  
  14.         }  
  15.         else  
  16.         {  
  17.             Console.WriteLine("No rows found.");  
  18.         }  
  19.         reader.Close();  
  20.     }  
  21. }  
DataReader

Thanks for reading this article. Hope you enjoyed it.