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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap