简体   繁体   中英

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

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);

Have you tried:

public Connection conn1;
conn1 = DriverManager.getConnection(connectionString1);
public Connection conn2;
conn2 = DriverManager.getConnection(connectionString2);
  1. Instance members shouldn't be public.

  2. Connection should be a local variable, not an instance member.

You can only connect to one database at a time with a single Connection. Ergo you need another Connection.

我认为你必须使用J2EE,JTA事务管理器来实现这一目标。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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