Generic coding with the ADO.NET common base classes
The .NET Framework, versions 2.0, 3.0, and 3.5, features
a namespace called System.Data.Common
, which features
a set of base classes that can be shared by any .NET data provider.
This facilitates a generic ADO.NET database application development
approach, featuring a constant programming interface across different
databases.
DbProviderFactory factory = DbProviderFactories.GetFactory("IBM.Data.DB2");
DbConnection conn = factory.CreateConnection();
DbConnectionStringBuilder sb = factory.CreateConnectionStringBuilder();
if( sb.ContainsKey( "Database" ) )
{
sb.Remove( "database" );
sb.Add( "database", "SAMPLE" );
}
conn.ConnectionString = sb.ConnectionString;
conn.Open();
The DbProviderFactory
object is the point where
any generic ADO.NET application begins. This object creates generic
instances of .NET data provider objects, such as connections, data
adapters, commands, and data readers, which work with a specific database
product. In the previous example, the "IBM.Data.DB2"
string passed into the GetFactory
method
uniquely identifies the IBM® Data
Server Provider for .NET, and results in the initialization of a DbProviderFactory
instance
that creates database provider object instances specific to the IBM Data Server Provider for .NET.
The DbConnection
object can connect to Db2® family
Informix® databases, just as a DB2Connection
object, which is actually inherited from DbConnection
.
Using the DbConnectionStringBuilder
class, you can determine the connection string
keywords for a data provider, and generate a custom connection string. The code in the previous
example checks if a keyword named "database"
exists in the IBM Data Server Provider for .NET, and if so, generates a connection string to
connect to the SAMPLE database.