Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple JDBC drivers in the same application?

Tags:

java

jdbc

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

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

returns SQL Server connections all after that.

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?

like image 263
Ivan Avatar asked Feb 18 '13 21:02

Ivan


2 Answers

You misunderstand. When you load a driver class with Class.forName(), that driver registers itself with the driver manager. 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.

However, rather than getting connections directly from the driver manager, I recommend that you use a connection pool (such as 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.

like image 150
parsifal Avatar answered Sep 22 '22 15:09

parsifal


You need to use DataSource. Configure a DataSource for each type of connection and the use the appropriate DataSource each time (e.g. via the proper DAO)

like image 29
Cratylus Avatar answered Sep 21 '22 15:09

Cratylus