C#ADO.NET中数据库驱动程序访问的通用方法

时间:2013-10-14 10:31:07

标签: database c#-4.0 jdbc ado.net

我必须编写一个小型C#程序,它将以动态方式处理至少三个不同的数据库供应商(Oracle,Sybase ASE,SqlServer)。 (它将依靠客户选择来选择数据库)

我决定通过ado.net数据提供商使用“纯”托管驱动程序。

但是,当我只是尝试连接时,我希望代码是“一行来统治它们”,就像JDBC一样:

DriverManager.getConnection(connection_string);

而不是这个,很惊讶,我必须为每个驱动程序编写其特定的代码:

SqlConnection() for SqlServer 

AseConnection() for Sybase

OracleConnection(), etc.

当然,我应该用自己封装 - 所有这些都在抽象方法和动态加载中,但我想知道为什么在.net中不存在这样的东西

嗯,我感觉我错过了什么

1 个答案:

答案 0 :(得分:6)

由于您在计算机上安装了相应数据库的.Net Provider,因此您可以使用DbProviderFactory作为示例:

包括

using System.Data.Common;

尝试这样的事情:

// create the provider factory from the namespace provider
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); 

// you could create any other provider factory.. for Oracle, MySql, etc...


// use the factory object to create Data access objects.
DbConnection connection = factory.CreateConnection(); // will return the connection object, in this case, SqlConnection ...

connection.ConnectionString = "read connection string from somewhere.. .config file for sample";


try
{
   // open connection
   connection.Open();

   // create command to execute queries...
   DbCommand command = connection.CreateCommand(); // create a SqlCommand, OracleCommand etc... depende of the provider factory configured.

   // some logic 
}
catch 
{
}
finally 
{
   // close connection
   connection.Close();
}

要知道,您的应用程序可以找到哪些提供程序,您可以使用DbProviderFactories.GetFactoryClasses()方法获取DataTable,其中包含计算机上安装的每个提供程序的详细信息。