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?
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.
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
)