gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:43:25 25 4
gpt4 key购买 nike

我正在为系统开发一个简单的数据库处理器,但我需要支持 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 接口(interface)(如 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 = ????
}

有没有快速的方法来做到这一点?

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

感谢您的关注!

最佳答案

使用工厂模式创建数据库连接。

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

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

关于c# - .NET 中的不可知连接处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com