Establishing different database connections with generic program by Santhosh_Mandadi


More Info
                                       Santhosh Reddy Mandadi

Sunday, May 13, 2012
Web URL:

Establishing different database connections with generic program
In my previous post, I've explained about establishing the connection. In this post, I'm now going to
cover a generic program which can be used to any database in run time dynamically (i.e.; without
changing the program source code). I'm going explain.

import java.sql.*;

public class GenericJDBCApp
  public static void main(String args[]) throws Exception
    String driverClass, jdbcURL, userName, password;
    //Reading the user defined system properties
    driverClass = System.getProperty("driverClass");
    jdbcURL = System.getProperty("jdbcURL");
    userName = System.getProperty("userName");
    password = System.getProperty("password");
    Connection connection = DriverManager.getConnection(jdbcURL, userName, password);
    DataBaseMetaData metaData = connection.getMetaData();
    System.out.println("Connected to...."+metaData.getDatabaseProductName()+"
    System.out.println("Supports stored procedures: "+metaData.suportsStoredProcedures());

If the above program is executed by using the following command, it will establish the connection with
java -DdriverClass=com.mysql.jdbc.Driver -DuserName=root -Dpassword=test -
DjdbcURL=jdbc:mysql://localhost:3308/test GenericJDBCApp

By changing the values of the system parameter, we can make the application connect to any other
database server.

DatabaseMetaData is an interface, when the above application eecutes connection.getMetaData(), the
code provided by the JDBC driver vendor will be executed and this code creates an object based on a
class provided by the vendor implemeting DatabaseMetaData.

To top