Computer programming: create connection using provider factory,c# code

The new ADO.NET classes that allow for generic data access functionality-such as DBConnection, DbCommand, and so on -are grouped under the System.Data.Common namespace.
The first step in implementing database-agnostic data access is to use the DBProviderFactory class to create a new database provider factory object.

 DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlCient");

This piece of code, because of the System.Data.SqlClient parameter passed, will have the factory object contain a SQLServer database provider factory ( the term factory generally refers to a class that builds class instances, or objects, for you). The System.Data.SqlClient string parameter is kept in a configuration file, allowing you to have c# code that really doesn't know what kind of database it's dealing with.

The database provider factory class is capable of creating a database-specific connection object through its CreateConnection method. However, you'll keep the reference to the connection object stored using the generic DbConnection reference:

 DbConnection conn = factory.CreateConnection();

The connection object will actually contain a SqlConnection object if the backend database in SQLServer, an OracleConnection if the backend database is Oracle, and so on. However, instead of working with SqlConnection or OracleConnection objects, we simply use DbConnection and let it decide at runtime what kind of object to create in the background.


Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites