Difference Between DataReader, DataSet, DataAdapter, and DataTable in C#

Difference Between DataReader, DataSet, DataAdapter, and DataTable in C#

Difference Between DataReader, DataSet, DataAdapter, and DataTable in C#

1. DataReader

The DataReader is a forward-only, read-only stream of data from a database. It is optimized for fast, efficient retrieval of data, making it ideal when you need to quickly read large amounts of data without needing to manipulate it.

Example:

SqlCommand command = new SqlCommand("SELECT * FROM Users", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(reader["Username"].ToString());
}
reader.Close();

2. DataSet

A DataSet is an in-memory representation of data that can hold multiple tables simultaneously. Unlike `DataReader`, a `DataSet` is disconnected from the data source and is useful for working with data in a disconnected environment.

Example:

DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Users", connection);
adapter.Fill(dataSet);

3. DataAdapter

The DataAdapter acts as a bridge between a `DataSet` and a data source for retrieving and saving data. It uses `Fill` to load data from the database into the `DataSet` and `Update` to save changes from the `DataSet` back to the database.

Example:

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Users", connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);

// Making changes to the DataSet
dataSet.Tables[0].Rows[0]["Username"] = "NewUsername";

// Updating the database
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(dataSet);

4. DataTable

A DataTable represents a single table of in-memory data. It is a part of the `DataSet`, but can also be used independently when you only need to work with one table at a time.

Example:

DataTable dataTable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Users", connection);
adapter.Fill(dataTable);
#CSharp #DataReader #DataSet #DataAdapter #DataTable #Programming #DotNet

Post a Comment

0 Comments