Monday, August 22, 2011

Five Ways to create a JDBC Connection


Creating the Connection from the database is a very resource consuming job. you can create a connection using many ways. Let me explain some way to obtain the Connection.
1) Using DriverManager's getConnection Method:
First way is to use the DriverManger's getConnection() method. this is a most popular way to create a Connection from Database.Following are the code. This method except three parameter. url, username and password.
  1. Connection con = DriverManager.getConnection(url,username,pass);
2) Using DriverManager's registerDriver method :
Second way to use registerDriver() method of DriverManager class. this method is static like first one and use a reference of Driver class or its subclass. Following is the code for demonstrating the same.
  1. DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
3) Using Properties Object:
Third way is to use Properties Object. Properties are used to configure the object. we can used this to pass all the details to getConnection() method. we can create the object and pass it to getConnection() overloaded method. Following is the code for getting connection for Oracle Database.
  1. Properties props = new Properties();
  2. props.put("user","scott");
  3. props.put("password","tiger");
  4. Connection c = DriverManager.getConnection(url, props);
4) Using properties file:
Properties file are the normal text file with .properties extension. Properties file is the old way to read the properties from the plain text file and populate it in Properties object. To follow this way just create a file with .properties extension and add all the properties into it. read the properties from file and populate in Properties Object. Following are the Code for the same.
  1. #MyDriverDetails.properties
  2. driverClassName =oracle.jdbc.driver.OracleDriver
  3. url=jdbc:oracle:thin:@mysys:1521:khan
  4. user=scott
  5. password=tiger
  1. FileInputStream fis=new FileInputStream("MyDriverDetails.properties");
  2. p.load(fis);
  3. Driver d=(Driver) Class.forName((String)p.get("driverClass")).newInstance();
  4. Connection con=d.connect((String)p.get("url"),p);
5) System.setProperty() method: 
the static setProperty() method of System class is used to set the system property. this method is using two argument. first the property name and second is the value. jdbc.driver is the property name and value is the driver class name. you can also pass this property while running the program.
  1. System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver");
  2. -- or --
  3. java -Djava.drivers=sun.jdbc.odbc.JdbcOdbcDriver MyJdbcExp1

No comments:

Post a Comment