Read Java JDBC Connection Details from Properties File


Read JDBC Configurations from Properties File

It is always better to keep the configuration details in the properties file, this helps you choose the Database and user details based on the environment like local/staging/uat/production.

Step 1: Create a local_configuration.properties file

local_configuration.properties
MYSQL_JDBC_DRIVER_CLASS=com.mysql.cj.jdbc.Driver
MYSQL_DB_URL=jdbc:mysql://localhost:3306/my_uat
MYSQL_DB_USER=root
MYSQL_DB_USER_PASSWORD=root123

Step 2: Reading the Properties File

InputStream inputStream = new FileInputStream("local_configuration.properties");
Properties properties = new Properties();
properties.load(inputStream);

String url = properties.getProperty("MYSQL_DB_URL");
String user = properties.getProperty("MYSQL_DB_USER");
String password = properties.getProperty("MYSQL_DB_USER_PASSWORD");

Step 3: Complete JDBC Code

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

public class JDBCReadFromPropertiesFile {

    public static void main(String[] args) throws SQLException, IOException {

        InputStream inputStream = new FileInputStream("local_configuration.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String url = properties.getProperty("MYSQL_DB_URL");
        String user = properties.getProperty("MYSQL_DB_USER");
        String password = properties.getProperty("MYSQL_DB_USER_PASSWORD");
        String sql = "Select * from students";

        Connection connection = DriverManager.getConnection(url, user, password);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);

        while(resultSet.next()) {
            System.out.print(resultSet.getInt(1)+"\t");
            System.out.print(resultSet.getString(2)+"\t");
            System.out.print(resultSet.getDate(3)+"\t");
            System.out.println();
        }
    }
    
}
Output:

1 Mike 2001-07-22
2 Alex 2002-08-13
3 Sam 2022-01-25



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.