.NET中的不可知连接处理程序

时间:2010-01-06 12:14:58

标签: c# database-connection database-agnostic

我正在为系统开发一个简单的数据库附件,但我需要支持2个数据库,PostgreSQL和Oracle(XXg);

一个例子就是这样(已经为pgsql工作)

... bunch of properties, constructors and fields

private String BuildConnectionString();

public Int32 ExecuteNonQuery(NpgsqlCommand sqlCommand);

public NpgsqlDataReader ExecuteQueryReader(NpgsqlCommand sqlCommand);

public Object ExecuteScalar(NpgsqlCommand sqlCommand);

我想知道是否有可能只使用System.Data接口构建一个类来处理这两个数据库,比如IDataReader,IDbConnection等。我想是的,但是当我需要实例时,我有点卡住连接。例如:

    public PgSqlConnectionHandler(String username, String password, 
               String database, String server, Int32 port)
    {
        this._username = username;
        this._password = password;
        this._database = database;

        this._server = server;
        this._port = port;

        this._connection = new NpgsqlConnection(BuildConnectionString());
    }

在另一种情况下,我会(_connection是typeof(IDbConnection):

public AgnosticConnectionHandler(String userName, String password, 
               String database, String server, Int32 port)
    {
        this._userName = userName;
        this._password = password;
        this._database = database;
        this._server = server;
        this._port = port;

        this._connection = ????
    }

有快速的方法吗?

这些是简单的数据库请求,我不需要任何花哨的东西,它是一个小系统。

感谢您的关注!

3 个答案:

答案 0 :(得分:2)

您可以使用IDbConnection接口,并创建工厂来创建具体类。然后,您可以从该接口创建IDbCommands并附加相应的参数并运行它们以获取DataReaders或DataSet。我之前做过这件事,效果很好。

答案 1 :(得分:2)

使用Factory Pattern创建数据库连接。

即,您有一个静态方法,可以创建一个连接,您可以在其中指定它的类型和所有相关信息,并返回接口(IDbConnection)(但在其构造中正确键入)。

此方法的核心可能是返回Oracle或Postgre连接的if语句。

答案 2 :(得分:2)

您也可以使用OleDb数据提供程序,因为两个数据库都有OLEDB提供程序。如果没有,您总是会ODBC,无论好坏。

alt text
(来源:microsoft.com