.NET API Documentation

System.Data.Common Namespace

The System.Data.Common namespace provides classes for creating data source–independent database connections, commands, and other objects that are used for interacting with databases. These classes enable developers to write provider‑independent data access code.

Key Types

TypeDescription
DbConnectionRepresents an open connection to a data source.
DbCommandExecutes a command against a data source.
DbDataAdapterFills a DataSet and updates a data source.
DbProviderFactoryCreates provider‑specific instances of the data source classes.
DbParameterRepresents a named parameter to a DbCommand.
DbConnectionStringBuilderBuilds a connection string for a data source.

Getting Started

Below is a simple example that demonstrates how to use the DbProviderFactory to create a connection and execute a command without referencing a specific provider.

// Add reference to System.Data.Common
using System;
using System.Data;
using System.Data.Common;

class Example
{
    static void Main()
    {
        // Obtain factory for the provider (e.g., System.Data.SqlClient)
        DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

        using (DbConnection conn = factory.CreateConnection())
        {
            conn.ConnectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
            conn.Open();

            using (DbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "SELECT TOP 5 * FROM Customers";
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine($"{reader["CustomerID"]} - {reader["CompanyName"]}");
                    }
                }
            }
        }
    }
}

Related Topics