About Properties Class

About Properties Class

In this tutorial, we are going to discuss about Properties Class. In Java Program if anything which changes frequently (like jdbc url, username, password etc) is not recommended to hard code in our program. The problem in this approach is if there is any change in java program, to reflect that change we have to recompile, rebuild and redeploy total application and even some times server restart also required,which creates a big business impact to the client.

About Properties Class

To overcome this problem, we should go for Properties file. The variable things we have to configure in Properties file and we have to read these properties from java program.

The main advantage of this approach is if there is any change in Properties file and to reflect that change just redeployment is enough, which won’t create any business impact to the client.

Example

db.properties

url =  jdbc:oracle:thin:@localhost:1521:XE
user = scott
password = tiger
import java.sql.*;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class JdbcPropertiesTest { 
   public static void main(String[] args) throws Exception {
      Properties prop = new Properties(); 
      FileInputStream fis = new FileInputStream("db.properties"); 
      prop.load(fis);// to load all properties from properties file into java Properties object
      String url = prop.getProperty("url"); 
      String user = prop.getProperty("user"); 
      String password = p.getProperty("password");
      String sqlQuery = "select * from emp"; 
      Class.forName("oracle.jdbc.OracleDriver"); 
      Connection con = DriverManager.getConnection(url,user,pwd); 
      Statement st = con.createStatement();
      boolean flag = false;
      ResultSet rs = st.executeQuery(sqlQuery);
      System.out.println("Eno\tEName\tESalary\tEAddress");
      while(rs.next()) {
         System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3)+"\t"+rs.getString(4));
      }
      if(flag==false) {
         System.out.println("No Records found");
      }
      con.close();
   }
}

If we change the properties in properties file for MySQL database then the program will fetch data from MySQL database.

db.properties

url =  jdbc:mysql://localhost:3306/ashokdb
user = ashok
password = chinni

How many getConnection() methods are available in DriverManager class?

Connection con = DriverManager.getConnection(url,user,pwd);
Connection con = DriverManager.getConnection(url,Properties);
Connection con = DriverManager.getConnection(url);

That’s all about the Properties Class. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

About Properties Class
Scroll to top