Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference two databases with Connection in java

I have two local databases I'm trying to connect to using Java's Connection class. It's easy enough to connect to the first database using:

public Connection conn;
conn = DriverManager.getConnection(connectionString);

How can I add a second database to that same connection? They're both on the same server so it should be fairly simple but I can't find the right commands to do it.

Thanks

like image 945
Zain Rizvi Avatar asked Oct 25 '11 07:10

Zain Rizvi


People also ask

Is it possible to connect to multiple databases in Java?

To connect to multiple databases in a single JDBC program you need to connect to the two (or more) databases simultaneously using the above steps. Here, in this example, we are trying to connect to Oracle and MySQL Databases where following are the URLs and sample user credentials of both databases.


2 Answers

A Connection is a session with a specific database. You can't use one Connection to communicate with two different databases; for that, you need two separate Connections.

Connection conn1 =  DriverManager.getConnection(connectionString1);
Connection conn2 =  DriverManager.getConnection(connectionString2);
like image 91
socha23 Avatar answered Nov 04 '22 13:11

socha23


Have you tried:

public Connection conn1;
conn1 = DriverManager.getConnection(connectionString1);
public Connection conn2;
conn2 = DriverManager.getConnection(connectionString2);
like image 35
Rohith Avatar answered Nov 04 '22 12:11

Rohith