How to write a JDBC application which connects to multiple databases simultaneously?


To connect with a database, you need to

  • Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class.

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
  • Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class.

Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");

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.

DatabaseURLUsernamePassword
Oraclejdbc:oracle:thin:@localhost:1521/xesystempassword
MySQLjdbc:mysql://localhost/rootpassword

Program

import java.sql.Connection;
import java.sql.DriverManager;
public class MultipleConnections {
   public static void main(String[] args) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      //Getting the connection
      String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
      Connection oracleCon = DriverManager.getConnection(oracleUrl, "system", "password");
      System.out.println("oracleConn=" + oracleCon);
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/";
      Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("mysqlConn=" + mysqlCon);
   }
}

Output

oracleConn = oracle.jdbc.driver.T4CConnection@6477463f
mysqlConn = com.mysql.jdbc.JDBC4Connection@3059cbc

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements