7

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

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

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

DriverManager.getConnection(connection_string);

取而代之的是,令人惊讶的是,我必须为每个驱动程序编写其特定代码:

SqlConnection() for SqlServer 

AseConnection() for Sybase

OracleConnection(), etc.

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

嗯,我感觉我错过了什么

4

1 回答 1

6

由于您在机器上安装了相应数据库的 .Net 提供程序,因此您可以使用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机器上安装的每个提供程序的详细信息。

于 2013-10-14T20:56:56.280 回答