Wednesday 6 June 2012

Developing Flexible JDBC Application

In Industry level if we develop N number of JDBC applications which deals specific database and if project client want to change the database then the java programmer has to modify N number of  JDBC applications which is the time consuming process  and hence Industry is not recommended to develop a specific JDBC applications. But Industry is always recommended to develop flexible JDBC Application


Def: a flexible JDBC application is one which will deal with any N number of databases without changing JDBC application code.

Steps to Develop Flexible Applications
1. Develop property file or resource bundle file which is having (key, value) pair
    where value of  key is always unique. where as value of value may or may not be unique.
    properties file is a text file which always residing in secondary memory.
    
    properties file(db.properties)
    driver=oracle.jdbc.driver.OracleDriver
    url=jdbc:oracle:thin:@localhost:1521:xe
    username=system
    password=manager
    tablename=emp
  
2. Inorder to read the data from properties file, properties file must be opened in read mode  with help of FileInputStream class
    ex: FileInputStream fis=new FileInputStream("db.properties");


3. To Transfer this Complete Data of Properties into main memory we need to use Properties class presented in java.util.* package
     ex: Properties p=new Properties(fis);


Example Program

import java.sql.*;
import java.io.*;
import java.util.*;
class first
{
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FileInputStream fis=new FileInputStream("db.prop");
Properties p=new Properties();
p.load(fis);
String d=p.getProperty("driver");
String url=p.getProperty("url");
String uname=p.getProperty("username");
String pwd=p.getProperty("password");
String tab=p.getProperty("tablename");
Class.forName(d);
Connection con=DriverManager.getConnection(url,uname,pwd);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from "+tab);
while(rs.next())
{
System.out.println(rs.getString(1)+"      "+rs.getString(2));
}
con.close();
}
}


No comments:

Post a Comment