How to connect database Dynamically in Java?

UPDATED: 09 September 2011
Hello friends I worked for J2EE and faced challenges regarding the database connection. We are working for java for long time but sometime we use complicated structure to do task. As we all know that to connect database we use the below code.
try {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con = DriverManager.getConnection("jdbc:mysql://x.x.x.x:3306/db", "username", "password");
} catch (Exception e) { e.printStackTrace(); }

Problem: When we have more then 50 Java file which use the same database. We put the above code in all file but the major problem arise when we need to change database URL, Username, Password. We have to go through each and every file and sometime we forgot to change the URL, Username, Password in some code and we will stuck with error. To come over this problem I did the simple logic which you all know but didn't came in your mind. So here I'm sharing the idea.

Step 1: Create bean file.
/* dbconnect.java */
public class dbconnect {
    private String _host = "jdbc:mysql://localhost:3306/db";
    private String username = "root";
    private String password = "root";
  
    public String getHost() {
        return _host;
    }
 
    public String getUsername() {
        return username;
    }
 
    public String getPassword() {
        return password;
    }
}
Step 2: Import above file in file where you want to use database.
/* getDetailsTest.java */
public class getDetailsTest {
    public static void main(String[] args) {
        dbconnect _db = new dbconnect();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(_db.getHost(), _db.getUsername(), _db.getPassword());
        } catch (Exception e) { e.printStackTrace(); }
    }
}
Now when you change the Host, Username, Password in dbconnect.java file. Now getDetailsTest.java file use new URL, Username, Password. No need to change 50 file for database connection. Just change one file.

2 comments :