What is ADO.NET?
ADO.NET (ActiveX Data Objects .NET) is a data access technology in the .NET framework that provides a set of classes and APIs for accessing and manipulating data from various data sources, such as databases, XML files, and web services. ADO.NET allows developers to build data-driven applications by providing a way to connect to data sources, retrieve data, perform data manipulation operations, and update data.
Here's a simple C# example that demonstrates how to use ADO.NET to connect to a database, retrieve data from a table, and display it:
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sqlQuery = "SELECT FirstName, LastName, Email FROM Customers";
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string firstName = reader["FirstName"].ToString();
string lastName = reader["LastName"].ToString();
string email = reader["Email"].ToString();
Console.WriteLine("Name: " + firstName + " " + lastName);
Console.WriteLine("Email: " + email);
Console.WriteLine();
}
}
}
}
Console.ReadLine();
}
}
In this example, we first establish a connection to the database by creating a SqlConnection object and providing the connection string that specifies the server, database, and authentication details.
We then define an SQL query to select data from the "Customers" table. We create a SqlCommand object, passing in the SQL query and the connection object.
Next, we execute the query using the ExecuteReader() method, which returns a SqlDataReader object. We iterate over the data using a while loop and retrieve the values of each column using the column names or indexes.
Finally, we display the retrieved data in the console.
Note: Remember to replace "YourServer" and "YourDatabase" in the connection string with the appropriate server and database names.
This example showcases a basic usage of ADO.NET to retrieve data from a database. ADO.NET provides many more features and capabilities, such as data insertion, updating, and deletion, handling transactions, and working with different data sources.