DATABASE PROGRAMMING WITH C# with an Introduction to ADO.
NET
ADO.NET is a set of classes that expose data access services for .NET Framework programmers. It
provides a bridge between the front-end applications and the back-end databases. ADO.NET is designed
to work with various data sources, including SQL Server, Oracle, and other databases.
Major Concepts
ADO.NET uses data providers to interact with databases. The main components of a data
provider are
Connection: Establishes a connection to the database
Command: Executes a command against the database (e.g., SQL queries).
Datareader: Reads a forward-only stream of data from the database.
DataAdapter: Fills a Dataset and updates the database.
A connection string is a string that specifies information about a data source and the means of
connecting to it. It typically includes the database server name, database name, user ID, and password.
A DataSet is an in-memory representation of data that can hold multiple tables and relationships between
them. It is disconnected from the database, allowing for data manipulation without a constant connection.
Setting Up ADO.NET
using System;
using System.Data;
using System.Data.SqlClient; // For SQL Server
Basic Operations with ADO.NET
string connectionString = "Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(connectionString))
connection.Open();
Console.WriteLine("Connection successful!");
Executing a SQL Command
string insertQuery = "INSERT INTO Students (Name, Age) VALUES (@Name, @Age)";
using (SqlCommand command = new SqlCommand(insertQuery, connection))
command.Parameters.AddWithValue("@Name", "John Doe");
command.Parameters.AddWithValue("@Age", 20);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"{rowsAffected} row(s) inserted.");
Reading Data with DataReader
string selectQuery = "SELECT Name, Age FROM Students";
using (SqlCommand command = new SqlCommand(selectQuery, connection))
using (SqlDataReader reader = command.ExecuteReader())
while (reader.Read())
Console.WriteLine($"Name: {reader["Name"]}, Age: {reader["Age"]}");
}
Using DataAdapter and DataSet
string selectQuery = "SELECT * FROM Students";
SqlDataAdapter adapter = new SqlDataAdapter(selectQuery, connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "Students");
foreach (DataRow row in dataSet.Tables["Students"].Rows)
Console.WriteLine($"Name: {row["Name"]}, Age: {row["Age"]}");
Error handling
try
// Database operations
catch (SqlException ex)
Console.WriteLine($"SQL Error: {ex.Message}");
catch (Exception ex)
Console.WriteLine($"Error: {ex.Message}");