SQL Data Access

Connecting to and Interacting with SQL Databases

This section covers the essential techniques and technologies for accessing data stored in SQL Server databases, including ADO.NET, ODBC, and OLE DB.

Introduction to Data Access

Accessing data is a fundamental aspect of any application that interacts with a database. SQL Server provides a robust and efficient set of tools and frameworks for developers to connect to, query, and manipulate data.

Microsoft's primary data access technology for .NET applications is ADO.NET. For broader compatibility and access from non-.NET applications, ODBC (Open Database Connectivity) and OLE DB remain important.

ADO.NET for SQL Server

ADO.NET is a set of classes in the .NET Framework that exposes the data access services of ADO. It provides a rich set of components for creating distributed, data-driven applications. Key components include:

Example: Connecting and Retrieving Data

Here's a basic C# example demonstrating how to connect to SQL Server and retrieve data using ADO.NET:

// Requires: using System.Data.SqlClient;

string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    string query = "SELECT CustomerID, CompanyName FROM Customers WHERE City = @City";

    using (SqlCommand command = new SqlCommand(query, connection))
    {
        // Add parameter to prevent SQL injection
        command.Parameters.AddWithValue("@City", "London");

        try
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Access data by column name or ordinal position
                    Console.WriteLine($"ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Connecting with ODBC and OLE DB

While ADO.NET is the preferred choice for .NET applications, ODBC and OLE DB provide alternatives:

Best Practices for Data Access