Thursday, 22 September 2016

Dealing with Flexible DB Connections

It is good programming practice to write the DB connections in a seperate property file. A property file is the text file where data is organised in the form of key and value pairs. In order to read the values from the properties file, we need to perform the following steps.

1. Create an Object for properties class which belongs to java.util package
      Eg: java.util.Properties p =new java.util.Properties();

2. Load the data from property file to properties object by invoking the following method
      public void load(FileInputStream);
      Eg: p.load("DB.properties");

3. Read property values from the properties object by using getProperty()
       public String getProperty(String);
       Eg:String driver=p.getProperty("DRIVER");


The following Java program illustrates the example of using properties file

package sample;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class ReadFlex {

 public static void main(String[] args) {

 Properties p = new Properties();
 try {
 p.load(new FileInputStream("data/db.properties"));
 } catch (IOException e) {
 e.printStackTrace();
 }
 String driver = p.getProperty("DRIVER");
 String url = p.getProperty("URL");
 String username = p.getProperty("USERNAME");
 String password = p.getProperty("PASSWORD");
 String table = p.getProperty("TABLE");

 // Registering the Driver
 try {
 Class.forName(driver);
 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 }

 try {
 // Establishing the Connection
 Connection con = DriverManager.getConnection(url, username, password);
 Statement st = con.createStatement();
 // Executing the Query
 ResultSet rs = st.executeQuery("Select * From " + table);
 ResultSetMetaData rsmd = rs.getMetaData();
 // Reading Records From The ResultSet
 while (rs.next()) {
 for (int c = 1; c <= rsmd.getColumnCount(); c++) {
 System.out.print(" " + rs.getString(c));
 }
 System.out.println("");
 }
 st.close();
 con.close();
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }

}

This program fetches all the records present in "actors" table. Here the program is referring the db.properties file which is in the data folder. The content in this properties file is as follows:
       DRIVER=oracle.jdbc.driver.OracleDriver
        URL=jdbc:oracle:thin:@localhost:1521:XE
        USERNAME=system
        PASSWORD=kiru
        TABLE=actors

The below image specifies the folder structure and the output of the program.

0 comments:

Post a Comment