Articles → ADO.NET → Writing Generic Data Access Code Using Dbproviderfactory Class
Writing Generic Data Access Code Using Dbproviderfactory Class
Software Requirement
Prerequisite Knowledge
- How to create projects (or websites) in Visual Studio?
- What is ADO.NET?
- How to use ADO.NET to connect to different data sources?
What Is A Data Source?
What Is A Data Provider In .Net?
What Is Generic Data Access Code?
Creation Of Access Data Source
Click to Enlarge
Creation Of SQL Server Data Source
Click to Enlarge
Adding Provider And Connection String In Web.Config File
<appSettings>
<add key="ProviderName" value="System.Data.SqlClient"/>
<!--<add key="ProviderName" value="System.Data.OleDb"/>-->
</appSettings>
<connectionStrings>
<add name="connectionString" connectionString="Data Source=TestServer\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=true;"/>
<!--<add name="connectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;data source=d:\test.mdb"/>-->
</connectionStrings>
Writing Generic Code
string commandText = "insert into books(BookName) values('test')";
DbProviderFactory factory = DbProviderFactories.GetFactory(ConfigurationManager.AppSettings["ProviderName"]);
using(DbConnection con = factory.CreateConnection()) {
using(DbCommand cmd = factory.CreateCommand()) {
con.ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
cmd.Connection = con;
cmd.CommandText = commandText;
con.Open();
cmd.ExecuteNonQuery();
}
}
Explanation Of Code
Output
Click to Enlarge
Change Provider And Connection String In Web.Config File
<appSettings>
<!--<add key="ProviderName" value="System.Data.SqlClient"/>-->
<add key="ProviderName" value="System.Data.OleDb"/>
</appSettings>
<connectionStrings>
<!--<add name="connectionString" connectionString="Data Source=TestServer\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=true;"/>-->
<add name="connectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;data source=d:\test.mdb "/>
</connectionStrings>
Output
Click to Enlarge
Conclusion