
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write JDBC Application to Connect 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.
Database | URL | Username | Password |
---|---|---|---|
Oracle | jdbc:oracle:thin:@localhost:1521/xe | system | password |
MySQL | jdbc:mysql://localhost/ | root | password |
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