使用JDBC连接到不同数据库的模式 [英] Pattern for connecting to different databases using JDBC

查看:568
本文介绍了使用JDBC连接到不同数据库的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个必须可配置的应用程序,以根据客户端的想法连接Oracle,SQL Server和MySQL。

I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.

到目前为止,我一直在计划使用JDBC-ODBC桥并只使用不同的连接字符串连接到数据库。

Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.

我被告知这不是很有效。


  1. 是否有连接多个数据库系统的模式或最佳实践?或者选择使用哪个驱动程序?

  1. Is there a pattern or best practice for connecting to multiple database systems? Or for selecting which driver to use?

我应该配置它吗?但包括所有三个驱动程序或构建三个单独的客户?

Should I have it configurable? but include all three drivers or build three separate clients?

我没有做任何复杂的事情只是抽水(插入)数据从事件流进入数据库。

I'm not doing anything complex just pumping (inserting) data into the database from an event stream.

推荐答案

我建议您将其配置为包含三个驱动程序。您可以使用这样的模式:创建一个提供连接数据库功能的超类(让我们称之为DAO)。这可能是抽象的。

I would suggest that you make it configurable and include the three drivers. You can use a pattern like this: Create a super class (lets call it DAO) that provides the functionality of connecting to the database. This could be abstract.

为您希望连接的每种类型的数据库创建一个具体的子类。所以你最终可能会得到MySQLDAO,MSSQLDAO和OracleDAO。每个都将加载相应的驱动程序并使用其各自的连接字符串。

Create a concrete sub class for each type of database that you wish to connect to. So you may end up with MySQLDAO, MSSQLDAO, and OracleDAO. each one will load the respective driver and use its respective connection string.

使用将创建实例的getDAO(DB)方法创建另一个类(让我们称之为DAOFactory) DAO取决于DB的值。

Create another class (lets call it DAOFactory) with a method getDAO(DB) that will create an instance of the DAO depending on the value of DB.

所以例如(在伪代码中):

So for instance(in Pseudocode):

 if(DB.equals("MySQL")){
    DAO = new MySQLDAO();
}
return DAO;

因此,任何需要连接到数据库的代码都会调用DAOFactory并请求DAO实例。您可以将DB值存储在外部文件(如属性文件)中,这样您就不必修改代码来更改数据库的类型。

So any code that needs to connect to the database will call the DAOFactory and ask for a DAO instance. You may store the DB value in an external file (like a properties file) so that you do not have to modify code to change the type of database.

这样你的代码不需要知道它连接到哪种类型的数据库,如果您决定稍后支持第四种类型的数据库,则必须再添加一个类并修改DAOFactory,而不是代码的其余部分。

this way your code does not need to know which type of database it is connecting to, and if you decide to support a fourth type of database later you will have to add one more class and modify the DAOFactory, not the rest of your code.

这篇关于使用JDBC连接到不同数据库的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆