In ADO.NET, fields are the individual columns of a database table. When you retrieve data from a database using ADO.NET, each row in the result set contains values for these fields. Let's break down how fields work with examples:
SqlConnection: Represents a connection to a SQL Server database. It doesn't directly deal with fields but is used to establish a connection to the database.
SqlCommand: Represents a SQL statement or stored procedure to execute against a SQL Server database. It specifies the query to retrieve or manipulate data, including the fields you want to work with.
SqlDataReader: Represents a forward-only stream of rows from a SQL Server database. When you execute a query using SqlCommand, SqlDataReader retrieves the results, allowing you to access the fields in each row.
Let's say you have a database table called "Employees" with fields like "ID", "Name", and "Age". Here's how you would use ADO.NET objects to retrieve data from this table:
Example
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void RetrieveData()
{
// Connection string to your database
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
// SQL query to retrieve data
string query = "SELECT ID, Name, Age FROM Employees";
// Create a SqlConnection to connect to the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand to execute the query
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
// Open the database connection
connection.Open();
// Execute the query and create a SqlDataReader
using (SqlDataReader reader = command.ExecuteReader())
{
// Loop through the rows of the result set
while (reader.Read())
{
// Access fields by their index or name
int id = reader.GetInt32(0); // Accessing field by index
string name = reader.GetString(1); // Accessing field by index
int age = reader.GetInt32(reader.GetOrdinal("Age")); // Accessing field by name
// Do something with the field values
Console.WriteLine($"ID: {id}, Name: {name}, Age: {age}");
}
}
}
catch (Exception ex)
{
// Handle any exceptions
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
}
}
In this example:
This is how you work with fields in ADO.NET using SqlConnection, SqlCommand, and SqlDataReader objects to retrieve data from a database table in an ASP.NET application.