Curriculum
SQL Connection, Commands, DataReader, DataAdapter, DataSet, Transactions, and Parameterized Queries in C# are the core building blocks of ADO.NET. Every enterprise-level .NET application interacts with databases using these components. Whether you are building an ASP.NET Core Application, Banking System, E-Commerce Platform, ERP Solution, CRM Software, Hospital Management System, or School Management System, understanding SQL Connection, Commands, DataReader, DataAdapter, DataSet, Transactions, and Parameterized Queries in C# is essential.
These components help applications connect to SQL Server, execute queries, retrieve records, update data, prevent security vulnerabilities, and ensure data consistency.
The typical workflow in ADO.NET is:
Application
↓
SqlConnection
↓
SqlCommand
↓
SQL Server
↓
Data Returned
↓
Application
This architecture enables communication between the application and database.
SqlConnection establishes communication with SQL Server.
Namespace:
using Microsoft.Data.SqlClient;
Example:
string connectionString =
"Server=localhost;Database=StudentDB;Trusted_Connection=True;";
SqlConnection connection =
new SqlConnection(
connectionString);
The connection object links the application to the database.
Example:
connection.Open();
Output:
Connection Opened
The application can now execute SQL commands.
Example:
connection.Close();
Output:
Connection Closed
Always close connections when work is complete.
Recommended approach:
using(
SqlConnection connection =
new SqlConnection(
connectionString))
{
connection.Open();
}
Benefits:
This approach is used in production applications.
SqlCommand executes SQL statements against SQL Server.
Example:
SqlCommand command =
new SqlCommand(
query,
connection);
SqlCommand is one of the most frequently used ADO.NET objects.
Example:
INSERT INTO Students
(
Name,
Course
)
VALUES
(
'Rahul',
'.NET'
)
C#:
string query =
@"INSERT INTO Students
(Name, Course)
VALUES
('Rahul','.NET')";
Execute:
command.ExecuteNonQuery();
Output:
Record Inserted
ExecuteNonQuery is used when no data is returned.
Examples:
INSERT
UPDATE
DELETE
CREATE TABLE
Return value:
Affected Rows
Example:
int rows =
command.ExecuteNonQuery();
Output:
1
One record was affected.
Example:
SELECT *
FROM Students
Command:
SqlCommand command =
new SqlCommand(
query,
connection);
Data retrieval requires a different execution method.
SqlDataReader retrieves records from SQL Server.
Characteristics:
Fast
Forward Only
Read Only
Connected Architecture
SqlDataReader is commonly used for high-performance data retrieval.
Example:
SqlDataReader reader =
command.ExecuteReader();
Read Records:
while(reader.Read())
{
Console.WriteLine(
reader["Name"]);
}
Output:
Rahul
Amit
Priya
Records are retrieved sequentially.
Example:
reader.Read();
Purpose:
Move to Next Record
Returns:
True
False
depending on whether records exist.
ExecuteScalar retrieves a single value.
Example:
SELECT COUNT(*)
FROM Students
C#:
object result =
command.ExecuteScalar();
Output:
100
Useful for aggregates and statistics.
Examples:
COUNT
SUM
AVG
MAX
MIN
Only the first column of the first row is returned.
SqlDataAdapter acts as a bridge between the database and DataSet.
Characteristics:
Disconnected Architecture
Automatic Data Transfer
Supports Updates
Useful for large applications.
Example:
SqlDataAdapter adapter =
new SqlDataAdapter(
query,
connection);
The adapter retrieves data from SQL Server.
A DataSet is an in-memory representation of data.
Characteristics:
Disconnected
Multiple Tables
Relations
XML Support
DataSet is useful for complex applications.
Example:
DataSet dataSet =
new DataSet();
adapter.Fill(
dataSet);
Output:
Data Loaded
The database connection can then be closed.
Example:
foreach(DataRow row
in dataSet.Tables[0].Rows)
{
Console.WriteLine(
row["Name"]);
}
Output:
Rahul
Amit
Priya
Data can be processed locally.
DataTable represents a single table in memory.
Example:
DataTable table =
new DataTable();
Benefits:
Lightweight
Easy to Use
In-Memory Processing
Frequently used with DataAdapters.
Example:
adapter.Fill(
table);
Output:
Records Loaded
The table now contains database records.
Objects:
SqlConnection
SqlCommand
SqlDataReader
Connection remains open.
Objects:
SqlDataAdapter
DataSet
DataTable
Connection closes after data retrieval.
A Transaction is a group of database operations that execute as a single unit.
Example:
Withdraw Money
Deposit Money
Both operations must succeed together.
Transactions ensure:
Critical business systems rely on transactions.
Example:
SqlTransaction transaction =
connection.BeginTransaction();
The transaction starts.
Example:
try
{
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
transaction.Commit();
}
catch
{
transaction.Rollback();
}
Output:
Success
or
Rollback
This ensures safe data processing.
Example:
transaction.Commit();
Changes are permanently saved.
Example:
transaction.Rollback();
All changes are reverted.
Essential for financial applications.
Parameterized Queries prevent SQL Injection attacks.
Bad Example:
string query =
"SELECT * FROM Users
WHERE Name='"
+ userInput + "'";
Danger:
SQL Injection
This approach should never be used.
Malicious Input:
' OR 1=1 --
Result:
SELECT *
FROM Users
WHERE Name=''
OR 1=1
All records may be exposed.
Example:
string query =
@"SELECT *
FROM Students
WHERE Name=@Name";
Parameter:
command.Parameters.AddWithValue(
"@Name",
"Rahul");
Execute:
SqlDataReader reader =
command.ExecuteReader();
This approach is secure.
Benefits:
Parameterized queries should always be used.
Transactions
Account Management
Statements
Orders
Payments
Inventory
Patients
Appointments
Medical Records
Students
Attendance
Results
ADO.NET powers all these systems.
Causes resource leaks.
Creates security vulnerabilities.
Can cause inconsistent data.
May block resources.
Store configuration externally.
SqlConnection establishes communication with SQL Server.
SqlCommand executes SQL statements.
SqlDataReader retrieves records using connected architecture.
DataSet stores multiple tables in memory.
A Transaction ensures multiple operations execute as a single unit.
Parameterized Queries prevent SQL Injection attacks.
SqlConnection establishes a connection with SQL Server.
SqlCommand executes SQL queries and database commands.
SqlDataReader retrieves records in a fast, forward-only, read-only manner.
DataSet is an in-memory collection of tables and relationships.
Transactions ensure data consistency and integrity.
They protect applications from SQL Injection attacks and improve security.
WhatsApp us