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.
Dname=sun.jdbc.odbc.JdbcOdbcDriver
URL=jdbc:mysql://localhost:3306/onlinetutorialspoint
Uname=root
password=123456
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 :
Dname=sun.jdbc.odbc.JdbcOdbcDriver
URL=jdbc:mysql://localhost:3306/onlinetutorialspoint
Uname=root
password=123456
JDBC_ReadDataFromProps.java
package com.onlinetutorialspoint.jdbc;
import java.io.FileInputStream;
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");
Class.forName(dname);
Connection con = DriverManager.getConnection(
url, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getString(3));
}
rs.close();
stmt.close();
con.close();
}
}
Output:
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:)