Execute SQL select query using Properties file

Q.  Write a program to execute SQL select query using Properties file.

Answer:

Properties file is a convenient way to store the data in key value pair. In properties file both key and values are of String type. We are storing the connection parameters in the properties file because we can manage the properties file very easily.

Don’t hard code any value in your Java application that are changeable in future, pass them to application from outside the application by taking the support of property file.

myfile.properties

my.driver = oracle.jdbc.driver.OracleDriver
my.dburl = jdbc:oracle:thin:@localhost:1521:XE
my.dbuser = local
my.dbpwd = test
my.sql = select * from employee



PropertiesTest.java

import java.sql.*;
import java.util.*;
import java.io.*;
class PropertiesTest
{
     public static void main(String[] args) throws Exception
     {
          //Locate text properties file
          FileInputStream fis = new FileInputStream("myfile.properties");
          //create an empty object of java.util.Properties class
          Properties prop = new Properties();
          //load the content of myfile.properties into java.util.Properties class
          prop.load(fis);
          //read value from java.util.Properties
          String dname = prop.getProperty("my.driver");
          String url = prop.getProperty("my.dburl");
          String user = prop.getProperty("my.dbuser");
          String pwd = prop.getProperty("my.dbpwd");
          String qry = prop.getProperty("my.sql");
          //create jdbc connection object
          Class.forName(dname);
          Connection con = DriverManager.getConnection(url, user, pwd);
          //create statement object
          Statement st = con.createStatement();
          ResultSet rs = st.executeQuery(qry);
          System.out.println("Id   Name");
          System.out.println("-------------");
          while (rs.next())
          {
               System.out.println(rs.getInt(1)+" "+
                    rs.getString(2));
          }
          System.out.println("-------------\n");
          rs.close();
          con.close();
          st.close();
     }
}


Output:

This application compiles successfully. When we run this program it will give the following result.

properties file