jdbc连接mysql不同的数据库,使用JDBC连接到不同数据库的模式

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

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

I'm told this is not very efficient.

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.

解决方案

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.

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.

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;

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值