Wednesday 1 October 2014

Can JDBC connect to more than one database ?

Yes, you can connect to more than one database. Lets say I created two databases named 'world' and 'sample'. Below application connects to both the databases.

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    static Connection conn;
    static Statement stmt;
    static ResultSet rs;
    
    /* Connect to database world */
    static Connection connectToWorld() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        
        String userName = "root";
        String password = "tiger";
        
        return DriverManager.getConnection(url,userName,password);
    }
    
     /* Connect to database sample */
    static Connection connectToSample() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String password = "tiger";
        
        return DriverManager.getConnection(url,userName,password);
    }
    
   public static void main(String args[]) throws SQLException, ClassNotFoundException{
        Connection conn1 = connectToWorld();
        Connection conn2 = connectToSample();

        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt1 = conn1.createStatement();
        Statement stmt2 = conn2.createStatement();
        stmt1.execute(query);     
        stmt2.execute(query);
        
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt1.execute(query);
        stmt2.execute(query);
        
        stmt1.close();
        stmt2.close();
        conn1.close();
        conn2.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Loading/Registering driver
Connecting to database
Dropping table employee


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment