In this tutorial, I am going to show how to prepare the JDBC connection with properties using a Java properties file.

When we write any JDBC application, we have to specify the specific details regarding driver name, URL, database user and password etc.. If you see in the previous basic JDBC Select Program Example we have created the connection with hard-coded values like below:

Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456");

For any reason If we want to change these details, we must have to change the Java program accordingly, and we have to recompile it. It leads to higher maintenance activity.

To avoid this complications typically we should have to read these details from a resoure bubdle file or a properties file. In this example, we are going to show how to read this connection informations from a properties file.

JDBC Connection with Properties File :

A resource bundle file or properties file is one which contains the data in the form of (key, value) pair.


Reading the data from Properties File:

To read the data from the resource bundle file, we have to open the resource bundle file in a reading mode with the help of the FileInputStream class.

FileInputStream fis=new FileInputStream (“connection.prop”);

Since files do not support to read data separately in the form of (key, value), hence, it is recommended to get the data of the file we must create an object of a predefined class called java.util.Properties.

Complete Example :

package com.onlinetutorialspoint.jdbc; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
import java.util.Properties; 
public class JDBC_ReadDataFromProps { 
    public static void main(String[] args) throws Exception { 
        FileInputStream fis=new FileInputStream("connection.prop"); 
        Properties p=new Properties (); 
        p.load (fis); 
        String dname= (String) p.get ("Dname"); 
        String url= (String) p.get ("URL"); 
        String username= (String) p.get ("Uname"); 
        String password= (String) p.get ("password"); 
        Connection con = DriverManager.getConnection( 
                url, username, password); 
        Statement stmt = con.createStatement(); 
        ResultSet rs = stmt.executeQuery("select * from student"); 
        while ( { 
            System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " 
                    + rs.getString(3)); 


28 Chandra Shekhar Banglore
30 Chandra Shekhar Banglore
101 Rajesh hyd
102 rajesh hyd
202 chandrashekhar hyderabad
2002 Rahul Banglore
2003 chandrashekhar hyderabad

Happy Learning:)