ADO.NET
ADO.NET
What is ADO.NET?
ADO stands for Microsoft ActiveX Data Objects
ADO.NET is one of Microsoft’s Data Access Technologies, which we can use to communicate with different data sources.
It is a part of the .NET Framework, which establishes a connection between the .NET Application and different data sources.
The Data Sources can be SQL Server, Oracle, MySQL, XML, etc. ADO.NET consists of a set of predefined classes that can be used to connect, retrieve, insert, update, and delete data
ADO.NET (ActiveX Data Objects .NET) is a data access technology in the Microsoft .NET framework that provides a set of libraries and classes for working with data from various sources, including databases, XML files, and more.
ADO.NET is designed to provide a bridge between your application code and the underlying data sources.
It offers a way to perform tasks like connecting to databases, executing queries, retrieving and updating data, and managing connections and transactions. This is especially important for building data-driven applications and services.
What Types of Applications Use ADO.NET?
ADO.NET can be used to develop any .NET application. The following are some of the .NET applications where you can use ADO.NET Data Access Technology to interact with a data source.
- ASP.NET Web Form Applications
- Windows Applications
- ASP.NET MVC Application
- Console Applications
- ASP.NET Web API Applications
- ASP.NET Core Applications
Components of ADO.NET
Components are designed for data manipulation and faster data access.
1.Connection,
2.Command,
3.DataReader,
4.DataAdapter,
5.DataSet
6.DataView
are the components of ADO.NET that are used to perform database operations.
- Connection: The Connection component establishes a connection to a data source, such as a database. It manages the underlying connection to the database server and provides methods to open and close the connection.
- Command: The Command component represents a command that is executed against a data source. It encapsulates SQL statements, stored procedure calls, and other database commands.
- DataReader: The DataReader component efficiently reads data from a data source. It provides a forward-only, read-only stream of data that is particularly useful for retrieving large datasets. Reading data with a DataReader is fast and memory-efficient.
- DataAdapter: The DataAdapter bridges the application’s DataSet (in-memory cache of data) and the data source. It facilitates the retrieval of data from the data source into the DataSet and also allows changes to be updated in the DataSet back to the data source.
- DataSet: The DataSet is an in-memory data cache that can hold multiple tables, relationships, and constraints. It allows disconnected data manipulation, meaning that data is retrieved from the data source, disconnected from the connection, and then manipulated without direct interaction with the data source. The Data Set can be considered an in-memory representation of the database.
- DataTable: A data table is a component within a Data Set that represents a table of data. It consists of rows and columns and allows you to store and manipulate tabular data. DataTables can have relationships and constraints to maintain data integrity.
- DataView: The DataView is used to filter, sort, and navigate through data within a DataTable. It provides a dynamic view of the data, allowing you to customize how it is presented to the user.
- Transaction: The Transaction component provides support for managing transactions in ADO.NET. Transactions group multiple data access operations into a single unit of work that can be either committed (made permanent) or rolled back (undone) as a whole.
- Connection String: The connection string is a configuration string that provides the necessary information to connect to a data source. It includes details such as the database server’s location, credentials, and other settings.
ADO.NET has two main components that are used for accessing and manipulating data. They are as follows:
- Data Provider and
- DataSet.
The Database can not directly execute our C# code; it only understands SQL. So, if a .NET application needs to retrieve data or to do some insert, update, and delete operations from or to a database, then the .NET application needs to
- Connect to the Database
- Prepare an SQL Command
- Execute the Command
- Retrieve the results and display them in the application
This is possible with the help of .NET Data Providers.
Different .NET Data Providers
Remember that the ADO.NET objects (Connection, Command, DataReader, and DataAdapter) have different prefixes depending on the provider, as shown below.
- Connection — SQLConnection, OracleConnection, OleDbConnection, OdbcConnection, etc.
- Command — SQLCommand, OracleCommand, OleDbCommand, OdbcCommand, etc.
- DataReader — SQLDataReader, OracleDataReader, OleDbDataReader, OdbcDataReader, etc.
- DataAdapter — SQLDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter, etc.
ADO.NET Data Providers are libraries or components facilitating communication between your .NET application and specific data sources, such as databases. They are responsible for connecting to the data source, executing queries, and managing data retrieval and updates.
- SqlClient: This is the ADO.NET Data Provider for Microsoft SQL Server. It provides optimized support for connecting to and interacting with SQL Server databases. The System.Data.SqlClient namespace contains classes like SqlConnection and SqlCommand.
- OleDb: The OleDb Data Provider allows you to connect to various data sources using the OLE DB technology. It can be used to connect to different databases, including Microsoft Access and other OLE DB-compatible data sources. The System.Data.OleDb namespace contains classes like OleDbConnection and OleDbCommand.
- Odbc: The Odbc Data Provider enables database connectivity using the ODBC (Open Database Connectivity) API. It supports a wide range of databases through ODBC drivers. The System.Data.Odbc namespace includes classes like OdbcConnection and OdbcCommand.
- OracleClient: This Data Provider connects to Oracle databases. Note that as of my last update in September 2021, Oracle has deprecated OracleClient, and using Oracle’s own .NET driver or other alternatives is recommended.
- SQLite: SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine. There are ADO.NET Data Providers specifically designed for SQLite, allowing you to work with SQLite databases in your .NET applications.
- MySqlClient: This Data Provider is used to connect to MySQL databases. It allows .NET applications to interact with MySQL database servers.
- Npgsql: Npgsql is a popular Data Provider for PostgreSQL databases. It supports connecting to and working with PostgreSQL databases in .NET applications.
- Other Third-Party Providers: Third-party ADO.NET Data Providers are also available for various other databases and data sources. The database vendors or other developers often create these providers to enhance connectivity.
DataSet:
The DataSet object in ADO.NET is not Provider-Specific. Once you connect to a database, execute the command and retrieve the data into the .NET application. The data can then be stored in a DataSet and work independently of the database. So, it is used to access data independently from any data source. The DataSet contains a collection of one or more DataTable objects.
When to use ADO.NET?
- Performance Optimization: If your application demands high performance and you need more control over data access operations, ADO.NET can provide more control over connection management, query execution, and data retrieval. This is useful when dealing with large datasets or complex queries.
- Data Source Variety: ADO.NET’s flexibility to work with various data sources beyond relational databases, such as XML files, can be beneficial when dealing with heterogeneous data storage scenarios.
- Ad Hoc Queries and Reports: If your application needs to generate dynamic or complex queries for ad hoc reporting or analysis, ADO.NET’s ability to dynamically construct and execute queries can be useful.
- Low-Level Data Manipulation: ADO.NET’s DataSet and DataTable structures allow you to work with disconnected data and perform various operations, such as sorting, filtering, and data transformation.
Methods of SqlCommand Class in C#
The SqlCommand class in C# provides the following methods.
- BeginExecuteNonQuery(): This method initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this System.Data.SqlClient.SqlCommand.
- Cancel(): This method tries to cancel the execution of a System.Data.SqlClient.SqlCommand.
- Clone(): This method creates a new System.Data.SqlClient.SqlCommand object is a copy of the current instance.
- CreateParameter(): This method creates a new instance of a System.Data.SqlClient.SqlParameter object.
- ExecuteReader(): This method Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection and builds a System.Data.SqlClient.SqlDataReader.
- ExecuteScalar(): This method Executes the query and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
- ExecuteNonQuery(): This method executes a Transact-SQL statement against the connection and returns the number of rows affected.
- Prepare(): This method creates a prepared version of the command on an instance of SQL Server.
- ResetCommandTimeout(): This method resets the CommandTimeout property to its default value.
ExecuteReader Method of SqlCommand Object in C#:
As we already discussed, this method sends the CommandText to the Connection and builds a SqlDataReader. When your T-SQL statement returns more than a single value (for example, rows of data), then you need to use the ExecuteReader method. Let us understand this with an example. The following example uses the ExecuteReader method of the SqlCommand object to execute the T-SQL statement, which returns multiple rows of data.
using Npgsql;
class ADONET
{
static NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=root;Database=windows_froms;");
ADONET()
{
if (conn != null)
{
Console.WriteLine("connection is done......");
}
else
{
Console.WriteLine("connection is not done");
}
}
public static void ExecuteReader()
{
//command
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM t_customer", conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("First Name: " + reader["c_fname"]);
Console.WriteLine("Last Name : " + reader["c_lname"]);
Console.WriteLine("Date of Birth: " + reader["c_dob"]);
Console.WriteLine("Email : " + reader["c_email"]);
Console.WriteLine("PIN : " + reader["c_pin"]);
Console.WriteLine("Contact : " + reader["c_contact"]);
Console.WriteLine("Profile Image: " + reader["c_profile_image"]);
Console.WriteLine("--------------------------");
}
conn.Close();
}
}
#region 21>ADO.NET
ADONET.ExecuteReader();
#endregionExecuteScalar Method of SqlCommand Object in C#:
When your T-SQL query or stored procedure returns a single (i.e., scalar) value, then you need to use the ExecuteScalar method of the SqlCommand object in C#. Let us understand this with an example. Now, we need to fetch the total number of records present in the Student table. It will return a single value, so this is an ideal situation to use the ExecuteScalar method. The following example will retrieve the total number of records present in the Student table.
using Npgsql;
class ADONET
{
static NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=root;Database=windows_froms;");
ADONET()
{
if (conn != null)
{
Console.WriteLine("connection is done......");
}
else
{
Console.WriteLine("connection is not done");
}
}
public static void ExecuteScalar(){
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT COUNT(*) FROM t_customer", conn);
object result=cmd.ExecuteScalar();
conn.Close();
Console.WriteLine("Total Rows: " + Convert.ToInt32(result));
}
}
#region 21>ADO.NET
ADONET.ExecuteScalar();
#endregionExecuteNonQuery Method of ADO.NET SqlCommand Object in C#:
When you want to perform Insert, Update, or Delete operations and return the number of rows affected by your query, you need to use the ExecuteNonQuery method of the SqlCommand object in C#. Let us understand this with an example. The following example performs Insert, Update, and Delete operations using the ExecuteNonQuery() method.
What is ADO.NET SqlDataReader Class in C#?
The ADO.NET SqlDataReader class in C# is used to read data from the SQL Server database in the most efficient manner. It reads data in the forward-only direction. It means once it reads a record, it will then read the next record; there is no way to go back and read the previous record.
- SqlDataReader is Connection-Oriented. It means it requires an open or active connection to the data source while reading the data. The data is available as long as the connection with the database exists.
- SqlDataReader is Read-Only. It means it is also not possible to change the data using SqlDataReader. You also need to open and close the connection explicitly.
- Forward-Only: The SqlDataReader works forwardly, meaning it can only read data in one direction — from the first to the last.
using Npgsql;
class ADONET
{
static NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=root;Database=windows_froms;");
ADONET()
{
if (conn != null)
{
Console.WriteLine("connection is done......");
}
else
{
Console.WriteLine("connection is not done");
}
}
public static void ExecuteScalar(){
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT COUNT(*) FROM t_customer", conn);
object result=cmd.ExecuteScalar();
conn.Close();
Console.WriteLine("Total Rows: " + Convert.ToInt32(result));
}
}
#region 21>ADO.NET
ADONET.ExecuteScalar();
#endregion- NextResult(): It advances the data reader to the next result when reading the results of batch Transact-SQL statements.
- Read(): It Advances the System.Data.SqlClient.SqlDataReader to the next record, returns true if there are more rows; otherwise, it is false.
How do you create an instance of the ADO.NET SqlDataReader class in C#?
You can not create the instance of SqlDataReader using the new keyword. Then, the question is how we get or create the instance of the SqlDataReader class. To create the instance of the SqlDataReader class, what you need to do is call the ExecuteReader method of the SqlCommand object, which will return an instance of the SqlDataReader class, as shown in the image below.
Example to Understand SqlDataReader in C#
In the example below, we access the data from the SqlDataReader object using the index number. Here, the index is starting from 0. So, the Name Index position is 0, the Email Index Position is 1, and the Mobile Index Position is 2. So, you can retrieve the data from the data reader by either using the string key or the Integer index position.
using Npgsql;
class ADONET
{
static NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=root;Database=windows_froms;");
ADONET()
{
if (conn != null)
{
Console.WriteLine("connection is done......");
}
else
{
Console.WriteLine("connection is not done");
}
}
public static void ExecuteReader()
{
//command
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM t_customer", conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("First Name: " + reader[1]);
Console.WriteLine("Last Name : " + reader[2]);
Console.WriteLine("Date of Birth: " + reader[3]);
Console.WriteLine("Email : " + reader[4]);
Console.WriteLine("PIN : " + reader[5]);
Console.WriteLine("Contact : " + reader[6]);
Console.WriteLine("Profile Image: " + reader[7]);
Console.WriteLine("--------------------------");
}
conn.Close();
}
}
#region 21>ADO.NET
ADONET.ExecuteReader();
#endregion
How to Access Multiple Result Sets Using DataReader in C#?
As of now, we have discussed how to retrieve the result set using the Read method of the Data Reader object. Now, you will understand how to access multiple result sets using a data reader.
public static void ExecuteReader_multipledataset()
{
//command
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM t_customer;select * from t_account;", conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("First Name: " + reader["c_fname"]);
Console.WriteLine("Last Name : " + reader["c_lname"]);
Console.WriteLine("Date of Birth: " + reader["c_dob"]);
Console.WriteLine("Email : " + reader["c_email"]);
Console.WriteLine("PIN : " + reader["c_pin"]);
Console.WriteLine("Contact : " + reader["c_contact"]);
Console.WriteLine("Profile Image: " + reader["c_profile_image"]);
Console.WriteLine("--------------------------");
// Console.WriteLine("First Name: " + reader[1]);
// Console.WriteLine("Last Name : " + reader[2]);
// Console.WriteLine("Date of Birth: " + reader[3]);
// Console.WriteLine("Email : " + reader[4]);
// Console.WriteLine("PIN : " + reader[5]);
// Console.WriteLine("Contact : " + reader[6]);
// Console.WriteLine("Profile Image: " + reader[7]);
// Console.WriteLine("--------------------------");
}
while (reader.NextResult())
{
while (reader.Read())
{
Console.WriteLine("Account Number : " + reader["c_account_num"]);
Console.WriteLine("ID : " + reader["c_id"]);
Console.WriteLine("Balance : " + reader["c_balance"]);
Console.WriteLine("Bank Name : " + reader["c_bank_name"]);
Console.WriteLine("IFSC Code : " + reader["c_ifsc_code"]);
Console.WriteLine("Created At : " + reader["c_created_at"]);
Console.WriteLine("Monthly Limit : " + reader["c_monthly_limit"]);
Console.WriteLine("-------------------------------");
}
}
conn.Close();
}When to Use ADO.NET SqlDataReader Class in C#?
Get Yashdesai’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are some situations where you might consider using SqlDataReader:
- High-Performance Data Reading: Use SqlDataReader when performance is critical. It is optimized for fast, efficient data reading and faster than other methods like DataTable or DataSet because it does not load all data into memory at once.
- Read-Only Data Access: If you only need to read data from the database and don’t need to perform any updates, inserts, or deletes, SqlDataReader is a suitable choice.
- Large Volume Data Processing: For processing large volumes of data, SqlDataReader is ideal because it reads data row-by-row, which means it uses less memory and can handle large datasets more efficiently.
- Sequential Data Access: When you need to access data sequentially, SqlDataReader is the way to go. It’s a forward-only reader, meaning you can only read data in the order it is received from the database.
- Data Binding in Web Applications: In web applications, SqlDataReader can be used for simple data binding scenarios where the data is displayed in data-bound controls and no manipulation or updates are required.
- Real-Time Data Display: For scenarios where data needs to be fetched and displayed in real-time, like in dashboards or reporting tools, SqlDataReader provides an efficient way to retrieve and present data quickly.
- Minimizing Memory Footprint: If you want to minimize the memory footprint of your application, SqlDataReader is a good choice as it does not store the entire dataset in memory.
- Streaming Data: SqlDataReader is suitable for streaming data scenarios, where you process data as it’s read without waiting for the entire set of data to be loaded.
Best Practices
- Using Statement: Always use a using statement for SqlDataReader and SqlConnection to ensure that resources are properly released.
- Exception Handling: Implement proper exception handling, especially for database operations, which can fail for various reasons.
- Performance Considerations: Since SqlDataReader is connected and forward-only, it’s very efficient for large data reads. However, ensure the database connection is not kept open longer than necessary.
- Read-only Access: Remember that SqlDataReader is read-only and forward-only. If you need more functionality, like editing data or moving back and forth, consider other ADO.NET objects like DataTable or DataSet.
ADO.NET SqlDataAdapter Class in C#
The ADO.NET SqlDataAdapter in C# bridges a DataSet or DataTable and a Data Source (SQL Server Database) to retrieve data. The SqlDataAdapter is a class that represents a set of SQL commands and a database connection. It is used to fill the DataSet or DataTable and update the data source as well.
How to create an instance of the C# SqlDataAdapter class in ADO.NET?
In order to create an instance of the SqlDataAdapter class in C#, we need to specify two things. The SQL command we want to execute and the connection we want to execute is like how we create the SqlCoomand object. Following is the syntax to create an instance of the SqlDataAdapter class.
Example to Understand ADO.NET SqlDataAdapter in C#
Now, we need to develop an application where we will fetch all the data from the student table, and then we need to display the student data in the console using SqlDataAdapter in C# using ADO.NET. Let us first write the code, and then we will understand the code.
public static void SqlDataAdapter_using_datatable()
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("SELECT * FROM t_customer", conn);
conn.Close();
System.Data.DataTable dt = new System.Data.DataTable();
dataAdapter.Fill(dt);
// Now you can iterate through the DataTable and display data
// foreach (DataRow row in dt.Rows)
// {
// Console.WriteLine(string.Join(", ", row.ItemArray)); // Printing all columns of each row
// }
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("First Name: " + row["c_fname"]);
Console.WriteLine("Last Name : " + row["c_lname"]);
Console.WriteLine("Date of Birth: " + row["c_dob"]);
Console.WriteLine("Email : " + row["c_email"]);
Console.WriteLine("PIN : " + row["c_pin"]);
Console.WriteLine("Contact : " + row["c_contact"]);
Console.WriteLine("Profile Image: " + row["c_profile_image"]);
Console.WriteLine("--------------------------");
}
}using Dataset
public static void SqlDataAdapter_using_dataset()
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("SELECT * FROM t_customer;select * from t_account", conn);
conn.Close();
System.Data.DataSet dt = new System.Data.DataSet();
dataAdapter.Fill(dt);
Console.WriteLine("tables : - " + dt.Tables.Count);
Console.WriteLine("table 1:- " + dt.Tables[0]);
Console.WriteLine("table 2:- " + dt.Tables[1]);
System.Data.DataTable table = dt.Tables[0];
foreach (DataRow row in table.Rows)
{
Console.WriteLine("First Name: " + row["c_fname"]);
Console.WriteLine("Last Name : " + row["c_lname"]);
Console.WriteLine("Date of Birth: " + row["c_dob"]);
Console.WriteLine("Email : " + row["c_email"]);
Console.WriteLine("PIN : " + row["c_pin"]);
Console.WriteLine("Contact : " + row["c_contact"]);
Console.WriteLine("Profile Image: " + row["c_profile_image"]);
Console.WriteLine("--------------------------");
}
}C# SqlDataAdapter using SQL Server Stored Procedure:
public static void SqlDataAdapter_using_storeprocedure()
{
try
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("select * from get_all_customers25()", conn);
dataAdapter.SelectCommand.CommandType = CommandType.Text; // Using CommandType.Text because it's a function call
System.Data.DataSet ds = new System.Data.DataSet();
dataAdapter.Fill(ds);
conn.Close();
Console.WriteLine("Tables : " + ds.Tables.Count);
if (ds.Tables.Count > 0)
{
Console.WriteLine("Table 1: ");
foreach (DataRow row in ds.Tables[0].Rows)
{
Console.WriteLine("First Name: " + row["c_fname1"]);
Console.WriteLine("Last Name : " + row["c_lname1"]);
Console.WriteLine("Date of Birth: " + row["c_dob1"]);
Console.WriteLine("Email : " + row["c_email1"]);
Console.WriteLine("PIN : " + row["c_pin1"]);
Console.WriteLine("Contact : " + row["c_contact1"]);
Console.WriteLine("Profile Image: " + row["c_profile_image1"]);
Console.WriteLine("--------------------------");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}- Disconnected Data Operations: If your application needs to work with data offline (i.e., without a continuous connection to the database), SqlDataAdapter is a good choice. It allows you to fill a DataSet or DataTable with data, manipulate it locally, and then apply changes back to the database.
- Caching and Offline Access: You can use SqlDataAdapter to populate a DataSet with data, store it in memory, and allow users to work with the data even when offline or disconnected from the database.
- Performance: In scenarios where you want to minimize the number of database round-trips while working with data, SqlDataAdapter allows you to fetch a bulk of data at once and work with it locally before applying changes back to the database.
- Batch Updates: SqlDataAdapter supports batch updates, where you can accumulate changes made to multiple rows in memory and then commit them to the database in a single batch. This can improve efficiency and reduce the number of round-trips to the database.
- Data Binding: If you’re building data-bound user interfaces, SqlDataAdapter simplifies the process. You can bind controls directly to the DataTable within a DataSet, making it easier to display and manipulate data.
limitations:
- It might not be as memory-efficient as using a SqlDataReader for large data sets, as it loads all the data into memory.
- It’s more suitable for scenarios where you have a relatively small number of rows compared to cases where you’re dealing with very large datasets.
What is ADO.NET DataTable in C#?
The DataTable in C# is similar to the Tables in SQL. That means the DataTable will also represent the relational data in tabular form.
you must have to include the System.Data namespace.
Properties of ADO.NET DataTable in C#:
The ADO.NET DataTable class in C# provides the following properties.
- Columns: It collects the columns that belong to this table.
- Constraints: t is used to get the collection of constraints maintained by this table.
- DataSet: It is used to get the Data Set to which this table belongs.
- DefaultView: It is used to get a customized view of the table that may include a filtered view.
- HasErrors: It is used to get a value indicating whether there are errors in any of the rows in the table of the DataSet.
- MinimumCapacity: It is used to get or set the initial starting size for this table.
- PrimaryKey: It is used to get or set an array of columns that function as primary keys for the data table.
- Rows: It is used to collect the rows that belong to this table.
- TableName: It is used to get or set the name of the DataTable.
Methods of C# DataTable in ADO.NET:
The C# DataTable class provides the following methods
- AcceptChanges(): It is used to commit all the changes made to this table.
- Clear(): It is used to clear the DataTable of all data.
- Clone(): It is used to clone the structure of the DataTable.
- Copy(): It is used to copy both the structure and data of the DataTable.
- CreateDataReader(): It returns a DataTableReader corresponding to the data within this DataTable.
- CreateInstance(): It is used to create a new instance of DataTable.
- GetRowType(): It is used to get the row type.
- GetSchema(): It is used to get the table schema.
- ImportRow(DataRow): It is used to copy a DataRow into a DataTable.
- Load(IDataReader): It is used to fill a DataTable with values from a data source using the supplied IDataReader.
- Merge(DataTable, Boolean): It merges the specified DataTable with the current DataTable.
- NewRow(): It creates a new DataRow with the same schema as the table.
- Select(): It is used to get an array of all DataRow objects.
- WriteXml(String): It is used to write the current contents of the DataTable as XML using the specified file.
When Should We Use ADO.NET DataTable in C#?
DataTable from ADO.NET is a versatile tool that serves as an in-memory representation of tabular data. It’s useful in various scenarios where you need to work with data in a structured format. Here are some situations where you might consider using DataTable:
- Disconnected Data Manipulation: When you need to work with data in a disconnected manner (i.e., without a continuous connection to the database), DataTable provides a way to load and manipulate data locally before synchronizing changes back to the database.
- Data Binding: If you’re building data-driven user interfaces, you can use DataTable as a data source for controls like grids, lists, and combo boxes. This allows you to display and interact with data in a user-friendly way.
- Complex Data Manipulation: In scenarios where you need to perform data manipulation operations like sorting, filtering, and grouping, DataTable provides built-in methods to achieve these tasks.
- Interchange Format: DataTable can serve as a container for data during data exchange between different layers of an application or even between different applications. You can serialize it to formats like XML or JSON for this purpose.
- Local Caching: If your application frequently accesses the same data, you can use DataTable to store a local copy of the data, reducing the need for frequent database queries.
- Small to Moderate Data Sizes: DataTable is suitable for managing data of moderate size. It’s not optimized for very large datasets, where other techniques like streaming and pagination might be more appropriate.
- Data Transformation: You can use DataTable to transform data from one format to another before sending it to another layer of your application or storing it in a different format.
- Batch Updates: If your application requires updating multiple records in a single transaction, you can accumulate changes in a DataTable and then perform a batch update to the database.
- Offline Access: In cases where users might need to work with data while disconnected from the network (e.g., in mobile applications), DataTable can store the required data for local usage.
- Data Validation: You can apply constraints and validation rules to columns within a Data Table to ensure data integrity before persisting changes to the database.
- For large datasets, a more memory-efficient approach like streaming with SqlDataReader or pagination might be better.
- For read-only scenarios, where you’re primarily retrieving data, using SqlDataReader or similar approaches can be more efficient.
- If your application is built around modern data-binding frameworks, they might offer more advanced data manipulation capabilities.
DataTable Methods in C#
Copying and Cloning the DataTable in C#:
If you want to create a full copy of a data table, then you need to use the Copy method of the DataTable object, which will copy the DataTable data and its schema. But if you want to copy the data table schema without data, then you need to use the Clone method of the data table. The following example shows the use of both the clone and copy methods.
System.Data.DataTable copytable = student.Copy();
Console.WriteLine("------------------------------copy table--------------------------------------");
foreach (DataRow row3 in copytable.Rows)
{
Console.WriteLine(row3["id"] + ", " + row3["Name"] + ", " + row3["Email"]);
}
Console.WriteLine("--------------------------------------------------------------------");
System.Data.DataTable clonetable = student.Clone();
clonetable.Rows.Add(1, "yash", "yash281@gmail.com");
clonetable.Rows.Add(2, "dev", "yash281@gmail.com");
clonetable.Rows.Add(3, "yash", "yash281@gmail.com");
Console.WriteLine("-------------------------------clone table--------------------------------");
foreach (DataRow row4 in clonetable.Rows)
{
Console.WriteLine(row4["id"] + ", " + row4["Name"] + ", " + row4["Email"]);
}
Deleting Data Row from a DataTable in C#:
You can delete a DataRow from the DataRowCollection by calling the Remove method of the DataRowCollection, or by calling the Delete method of the DataRow object.
The Remove method will remove the row from the collection, whereas the Delete method marks the DataRow for removal. The actual removal will occur when you call the AcceptChanges method. If you want to roll back, then you need to use the RejectChanges method, which will roll back to the previous state. The RejectChanges method will copy the Original data row version to the Current data row version.
DataRow row = student.Rows.Find(102);
if (row != null)
{
student.Rows.Remove(row);
}using Npgsql;
using System.Data;
class ADONET
{
static NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=root;Database=windows_froms;");
ADONET()
{
if (conn != null)
{
Console.WriteLine("connection is done......");
}
else
{
Console.WriteLine("connection is not done");
}
}
public static void ExecuteReader()
{
//command
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM t_customer", conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("First Name: " + reader["c_fname"]);
Console.WriteLine("Last Name : " + reader["c_lname"]);
Console.WriteLine("Date of Birth: " + reader["c_dob"]);
Console.WriteLine("Email : " + reader["c_email"]);
Console.WriteLine("PIN : " + reader["c_pin"]);
Console.WriteLine("Contact : " + reader["c_contact"]);
Console.WriteLine("Profile Image: " + reader["c_profile_image"]);
Console.WriteLine("--------------------------");
// Console.WriteLine("First Name: " + reader[1]);
// Console.WriteLine("Last Name : " + reader[2]);
// Console.WriteLine("Date of Birth: " + reader[3]);
// Console.WriteLine("Email : " + reader[4]);
// Console.WriteLine("PIN : " + reader[5]);
// Console.WriteLine("Contact : " + reader[6]);
// Console.WriteLine("Profile Image: " + reader[7]);
// Console.WriteLine("--------------------------");
}
conn.Close();
}
public static void ExecuteReader_multipledataset()
{
//command
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM t_customer;select * from t_account;", conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("First Name: " + reader["c_fname"]);
Console.WriteLine("Last Name : " + reader["c_lname"]);
Console.WriteLine("Date of Birth: " + reader["c_dob"]);
Console.WriteLine("Email : " + reader["c_email"]);
Console.WriteLine("PIN : " + reader["c_pin"]);
Console.WriteLine("Contact : " + reader["c_contact"]);
Console.WriteLine("Profile Image: " + reader["c_profile_image"]);
Console.WriteLine("--------------------------");
// Console.WriteLine("First Name: " + reader[1]);
// Console.WriteLine("Last Name : " + reader[2]);
// Console.WriteLine("Date of Birth: " + reader[3]);
// Console.WriteLine("Email : " + reader[4]);
// Console.WriteLine("PIN : " + reader[5]);
// Console.WriteLine("Contact : " + reader[6]);
// Console.WriteLine("Profile Image: " + reader[7]);
// Console.WriteLine("--------------------------");
}
while (reader.NextResult())
{
while (reader.Read())
{
Console.WriteLine("Account Number : " + reader["c_account_num"]);
Console.WriteLine("ID : " + reader["c_id"]);
Console.WriteLine("Balance : " + reader["c_balance"]);
Console.WriteLine("Bank Name : " + reader["c_bank_name"]);
Console.WriteLine("IFSC Code : " + reader["c_ifsc_code"]);
Console.WriteLine("Created At : " + reader["c_created_at"]);
Console.WriteLine("Monthly Limit : " + reader["c_monthly_limit"]);
Console.WriteLine("-------------------------------");
}
}
conn.Close();
}
public static void ExecuteScalar()
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT COUNT(*) FROM t_customer", conn);
object result = cmd.ExecuteScalar();
conn.Close();
Console.WriteLine("Total Rows: " + Convert.ToInt32(result));
}
public static void SqlDataAdapter_using_datatable()
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("SELECT * FROM t_customer", conn);
conn.Close();
System.Data.DataTable dt = new System.Data.DataTable();
dataAdapter.Fill(dt);
// Now you can iterate through the DataTable and display data
// foreach (DataRow row in dt.Rows)
// {
// Console.WriteLine(string.Join(", ", row.ItemArray)); // Printing all columns of each row
// }
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("First Name: " + row["c_fname"]);
Console.WriteLine("Last Name : " + row["c_lname"]);
Console.WriteLine("Date of Birth: " + row["c_dob"]);
Console.WriteLine("Email : " + row["c_email"]);
Console.WriteLine("PIN : " + row["c_pin"]);
Console.WriteLine("Contact : " + row["c_contact"]);
Console.WriteLine("Profile Image: " + row["c_profile_image"]);
Console.WriteLine("--------------------------");
}
}
public static void SqlDataAdapter_using_dataset()
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("SELECT * FROM t_customer;select * from t_account", conn);
conn.Close();
System.Data.DataSet dt = new System.Data.DataSet();
dataAdapter.Fill(dt);
Console.WriteLine("tables : - " + dt.Tables.Count);
Console.WriteLine("table 1:- " + dt.Tables[0]);
Console.WriteLine("table 2:- " + dt.Tables[1]);
System.Data.DataTable table = dt.Tables[0];
foreach (DataRow row in table.Rows)
{
Console.WriteLine("First Name: " + row["c_fname"]);
Console.WriteLine("Last Name : " + row["c_lname"]);
Console.WriteLine("Date of Birth: " + row["c_dob"]);
Console.WriteLine("Email : " + row["c_email"]);
Console.WriteLine("PIN : " + row["c_pin"]);
Console.WriteLine("Contact : " + row["c_contact"]);
Console.WriteLine("Profile Image: " + row["c_profile_image"]);
Console.WriteLine("--------------------------");
}
}
public static void SqlDataAdapter_using_storeprocedure()
{
try
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("select * from get_all_customers25()", conn);
dataAdapter.SelectCommand.CommandType = CommandType.Text; // Using CommandType.Text because it's a function call
System.Data.DataSet ds = new System.Data.DataSet();
dataAdapter.Fill(ds);
conn.Close();
Console.WriteLine("Tables : " + ds.Tables.Count);
if (ds.Tables.Count > 0)
{
Console.WriteLine("Table 1: ");
foreach (DataRow row in ds.Tables[0].Rows)
{
Console.WriteLine("First Name: " + row["c_fname1"]);
Console.WriteLine("Last Name : " + row["c_lname1"]);
Console.WriteLine("Date of Birth: " + row["c_dob1"]);
Console.WriteLine("Email : " + row["c_email1"]);
Console.WriteLine("PIN : " + row["c_pin1"]);
Console.WriteLine("Contact : " + row["c_contact1"]);
Console.WriteLine("Profile Image: " + row["c_profile_image1"]);
Console.WriteLine("--------------------------");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
public static void SqlDataAdapter_using_dataset_batch_update()
{
conn.Open();
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("SELECT * FROM student", conn);
NpgsqlCommandBuilder commandBuilder = new NpgsqlCommandBuilder(dataAdapter);
conn.Close();
System.Data.DataSet dt = new System.Data.DataSet();
dataAdapter.Fill(dt);
Console.WriteLine("table count :- " + dt.Tables.Count);
System.Data.DataTable student = dt.Tables[0];
foreach (DataRow row in student.Rows)
{
Console.WriteLine("id= " + row["s_id"] + " name = " + row["s_name"] + " phone = " + row["s_pho"] + " email = " + row["s_email"]);
}
Console.WriteLine("--------------------------------------------------------------------");
student.PrimaryKey = new DataColumn[] { student.Columns["s_id"] };
DataRow row1 = student.Rows.Find(1);
if (row1 != null)
{
Console.WriteLine("----------------------------------find data in student----------------------------------");
Console.WriteLine("id= " + row1["s_id"] + " name = " + row1["s_name"] + " phone = " + row1["s_pho"] + " email = " + row1["s_email"]);
row1["s_name"] = "yash";
}
else
{
Console.WriteLine("row not found");
}
Console.WriteLine("--------------------------------------------------------------------");
foreach (DataRow row in student.Rows)
{
Console.WriteLine("id= " + row["s_id"] + " name = " + row["s_name"] + " phone 000000= " + row["s_pho"] + " email = " + row["s_email"]);
}
Console.WriteLine("--------------------------------------------------------------------");
DataRow row2 = student.Rows.Find(9);
if (row2 != null)
{
Console.WriteLine("----------------------------------find data in student----------------------------------");
Console.WriteLine("id= " + row2["s_id"] + " name = " + row2["s_name"] + " phone = " + row2["s_pho"] + " email = " + row2["s_email"]);
row2.Delete();
}
else
{
Console.WriteLine("row not found");
}
//student.AcceptChanges();
student.RejectChanges();
Console.WriteLine("--------------------------------------------------------------------");
foreach (DataRow row in student.Rows)
{
if (row.RowState != DataRowState.Deleted) // Skip deleted rows
{
Console.WriteLine("id= " + row["s_id"] + " name = " + row["s_name"] + " phone = " + row["s_pho"] + " email = " + row["s_email"]);
}
}
Console.WriteLine("--------------------------------------------------------------------");
student.Rows.Add(3, "vedu", 45484815, "vedu55@gmail.com");
dataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand();
dataAdapter.DeleteCommand = commandBuilder.GetDeleteCommand();
dataAdapter.InsertCommand = commandBuilder.GetInsertCommand();
int rowsAffected1 = dataAdapter.Update(student);
Console.WriteLine($"Rows affected in student: {rowsAffected1}");
}
}
What is ADO.NET DataSet in C#?
The DataSet represents a subset of the database in memory. That means the ADO.NET DataSet is a collection of tables containing relational data in memory in tabular format.
It does not require a continuous open or active connection to the database. The DataSet is based on the disconnected architecture.
Note: The ADO.NET DataSet class is the core component for providing data access in a distributed and disconnected environment. The ADO.NET DataSet class belongs to the System.Data namespace.
Example to understand DataSet in C#:
Let us understand how to create and use ADO.NET DataSet in C# with an example. Here, we want to create two data tables (Customers and Orders), and then we want to add both these data tables to the DataSet, and then we want to log the data into the console.
Creating Customers Data Table:
We have already discussed how to create a Data Table in our previous article. If you have not read that article, please read our ADO.NET DataTable article before proceeding. Please have a look at the below image. As you can see here, we created one DataTable with the name Customer. Then we created three data columns (ID of type Int32, Name of type string, and Mobile of type string) and added these three columns to the Customer data table. Finally, we created two data rows and added these two data rows to the Customer data table.
Creating Orders Data Table:
Please have a look at the following image. Here, you can see we created the DataTable with the name Orders. Then we created three data columns (Id of type Int32, CustomerId of type Int32, and Amount of type Int32) and added these three data columns to the Orders data table. Finally, we created two data rows and added these two data rows to the Orders data table.
Creating DataSet with DataTable:
As we already discussed, the DataSet is a collection of data tables. So, let’s create a DataSet object and then add the two data tables (Customers and Orders) into the DataSet. Please have a look at the following image. Here, first, we created an instance of the DataSet and then added the two data tables using the Tables property of the DataSet object.
Fetch DataTable from DataSet:
Now, let us see how to fetch the data table from the dataset. You can fetch the data table from a dataset in two ways i.e. using the index position and using the table name (if provided).
Fetching DataTable from DataSet using index position:
As we first add the Customers table to DataSet, the Customer table Index position is 0. If you want to iterate through the Customer’s table data, you could use a for-each loop to iterate, as shown in the image below.
Fetching DataTable From DataSet using Name:
The second data table we added to the dataset is Orders, which will be added at index position 1. Further, if you notice, while creating the data table, we have provided a name for the data table, i.e., Orders. Now, if you want to fetch the data table from the dataset, then you can use the name instead of the index position. The following image shows how to fetch the data table using the name and looping through the data using a for each loop.
ADO.NET DataView Class in C#:
we can display or represent the DataTable’s data in various styles, or formats. For example, using DataView we can display the DataTable data in various sorting orders, and we can also filter the DataTable’s data. And the most important point is that we can create any number of DataViews for a single DataTable to respreset the data in different formats.
DataView represents a data-bindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.
Syntax: DataView dataView = new DataView(dataTable);
Syntax: DataView dataView = dataTable.DefaultView;
Displaying a Dataview in C#:
Using a for loop and using the integer index position, we can access the elements of a data view as follows:
Using For Loop to access the DataView
for(int i = 0; i<dataView.Count;i++)
{
Console.WriteLine(dataView[i][“DataTableColumnName”]);
}
Using Foreach Loop to access the DataView
foreach (DataRowView rowView in dataView1)
{
DataRow = rowView.Row;
Console.WriteLine(row[“DataTableColumnName”]);
}
- Sort: This property is used to get or set the sort column or columns, and sort order for the DataView. It returns a string that contains the column name followed by “ASC” (ascending) or “DESC” (descending). Columns are sorted ascending by default. Multiple columns can be separated by commas.
- RowFilter: This property is used to get or get the expression used to filter which rows are viewed in the DataView. It returns a string that specifies how rows are to be filtered.
using System.Data;
using Npgsql;
class Dataview_prc
{
static NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=root;Database=windows_froms;");
public Dataview_prc()
{
if (conn != null)
{
Console.WriteLine("connection is done......");
}
else
{
Console.WriteLine("connection is not done");
}
}
public static void dataview()
{
NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("SELECT Id, Name, Email, Mobile, Age, Salary, Department FROM EMPLOYEE", conn);
System.Data.DataTable EmployeeDataTable = new System.Data.DataTable();
dataAdapter.Fill(EmployeeDataTable);
DataView dataView1 = new DataView(EmployeeDataTable);
//dataView1.Sort="Age ASC";
//dataView1.Sort="Age ASC,name DESC";
//dataView1.RowFilter="Age >=27";
//dataView1.RowFilter = "Age >= 27 AND name LIKE '%a%'";
//dataView1.RowFilter = "Age >= 25 AND Department='IT'";
// dataView1.AllowNew = true;
// DataRowView newRow = dataView1.AddNew();
// newRow["Name"] = "yash";
// newRow["Email"] = "Ayash.net";
// newRow["Mobile"] = "1234567890";
// newRow["Age"] = 25;
// newRow["Salary"] = 10000;
// newRow["Department"] = "IT";
//dataView1.AllowEdit = true;
dataView1.AllowDelete = true;
// display
foreach (DataRowView rowView in dataView1)
{
DataRow row = rowView.Row;
// if(row["Department"].ToString()=="IT"){
// rowView.Delete();
// }
//Console.WriteLine("------------------------------------update------------------------------------------");
Console.WriteLine($"Id: {row["Id"]}, Name: {row["name"]}, Age: {row["Age"]}, Salary: {row["Salary"]}, Department: {row["Department"]}");
// row["Salary"] = Convert.ToInt32(row["Salary"]) + 1000;
// Console.WriteLine($"Id: {row["Id"]}, Name: {row["name"]}, Age: {row["Age"]}, Salary: {row["Salary"]}, Department: {row["Department"]}");
}
// foreach (DataRowView rowView in dataView1)
// {
// DataRow row = rowView.Row;
// Console.WriteLine($"Id: {row["Id"]}, Name: {row["name"]}, Age: {row["Age"]}, Salary: {row["Salary"]}, Department: {row["Department"]}");
// }
}
}






