简体   繁体   English

如何在同一个应用程序中使用多个JDBC驱动程序?

[英]How to use multiple JDBC drivers in the same application?

As far as I understand, as soon as I execute 据我所知,只要我执行

Class.forName("net.sourceforge.jtds.jdbc.Driver");

I initialize the application to use JTDS SQL Server driver globally and 我初始化应用程序以全局使用JTDS SQL Server驱动程序

java.sql.DriverManager.getConnection(url, user, password);

returns SQL Server connections all after that. 之后返回SQL Server连接。

But what if I want to work with multiple different database engines in the same function, getting a JTDS SQL Server connection, then, for example a PostgreSQL connection and then a new JTDS SQL Server connection again? 但是,如果我想在同一个函数中使用多个不同的数据库引擎,获得JTDS SQL Server连接,然后,例如PostgreSQL连接,然后再次使用新的JTDS SQL Server连接,该怎么办?

You misunderstand. 你误会了。 When you load a driver class with Class.forName() , that driver registers itself with the driver manager. 当您使用Class.forName()加载驱动程序类时,该驱动程序将自己注册到驱动程序管理器。 You can do this with as many drivers as you want. 您可以使用任意数量的驱动程序执行此操作。

The first parameter of getConnection() is a URL that will uniquely identify the driver to use for that connection. getConnection()的第一个参数是一个URL,它将唯一标识用于该连接的驱动程序。

However, rather than getting connections directly from the driver manager, I recommend that you use a connection pool (such as Apache DBCP ). 但是,我建议您使用连接池(例如Apache DBCP ),而不是直接从驱动程序管理器获取连接。 This will let you get connections on an as-needed basis, and will provide some additional functionality such as warning you if you forget to return the connection to the pool. 这将允许您根据需要获得连接,并将提供一些其他功能,例如,如果您忘记将连接返回到池,则会发出警告。

You need to use DataSource . 您需要使用DataSource Configure a DataSource for each type of connection and the use the appropriate DataSource each time (eg via the proper DAO ) 为每种类型的连接配置DataSource ,并且每次都使用适当的DataSource (例如,通过适当的DAO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM