Documentation

ADO.NET Connection Objects

Connection objects are fundamental to interacting with a data source in ADO.NET. They represent an open connection to a data source, allowing you to execute commands and retrieve data.

Introduction to Connection Objects

Every ADO.NET data provider (such as SQL Server, Oracle, OleDb, ODBC) exposes its own set of connection objects. While the specific implementation details may vary, they all adhere to a common interface and offer similar core functionality.

Key Properties and Methods

Connection objects provide several essential properties and methods:

Working with Connection Objects

Here's a typical workflow for using a connection object:

  1. Instantiate the appropriate connection object for your data provider.
  2. Set the ConnectionString property.
  3. Call the Open() method to establish the connection.
  4. Create and execute Command objects using the open connection.
  5. Process the results returned by the commands.
  6. Call Close() or Dispose() to release resources.

Best Practice: Always enclose connection objects within a using statement (in C#) or use a try...finally block to ensure that the connection is properly closed and disposed of, even if errors occur.

Example: Connecting to a SQL Server Database (C#)

C#
using System;
using System.Data;
using System.Data.SqlClient;

public class ConnectionExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

        // Using statement ensures that Dispose() is called automatically
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                Console.WriteLine("Connection State: " + connection.State);
                Console.WriteLine("Successfully connected to the database.");

                // Here you would typically create and execute Command objects
                // SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM MyTable", connection);
                // int count = (int)command.ExecuteScalar();
                // Console.WriteLine("Number of records: " + count);

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error connecting to the database: " + ex.Message);
            }
            finally
            {
                // The 'using' statement handles closing and disposing
                Console.WriteLine("Connection State after block: " + connection.State);
            }
        }
    }
}

Example: Connecting to a SQL Server Database (VB.NET)

VB.NET
Imports System
Imports System.Data
Imports System.Data.SqlClient

Public Class ConnectionExample
    Public Shared Sub Main(args As String())
        Dim connectionString As String = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"

        ' Using statement ensures that Dispose() is called automatically
        Using connection As New SqlConnection(connectionString)
            Try
                connection.Open()
                Console.WriteLine("Connection State: " & connection.State.ToString())
                Console.WriteLine("Successfully connected to the database.")

                ' Here you would typically create and execute Command objects
                ' Dim command As New SqlCommand("SELECT COUNT(*) FROM MyTable", connection)
                ' Dim count As Integer = CInt(command.ExecuteScalar())
                ' Console.WriteLine("Number of records: " & count.ToString())

            Catch ex As SqlException
                Console.WriteLine("Error connecting to the database: " & ex.Message)
            Finally
                ' The 'using' statement handles closing and disposing
                Console.WriteLine("Connection State after block: " & connection.State.ToString())
            End Try
        End Using
    End Sub
End Class

Connection Pooling

ADO.NET providers often implement connection pooling. This is a performance optimization where instead of opening and closing a connection for every request, a pool of connections is maintained. When a connection is requested, it's taken from the pool. When it's closed, it's returned to the pool to be reused.

Connection pooling is typically enabled by default for most providers. You can control its behavior through specific keywords in the connection string.

Error Handling

When working with connections, it's essential to handle potential exceptions. Common exceptions include:

Related Topics