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
Type | Description |
---|---|
DbConnection | Represents an open connection to a data source. |
DbCommand | Executes a command against a data source. |
DbDataAdapter | Fills a DataSet and updates a data source. |
DbProviderFactory | Creates provider‑specific instances of the data source classes. |
DbParameter | Represents a named parameter to a DbCommand . |
DbConnectionStringBuilder | Builds 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"]}");
}
}
}
}
}
}