Reading External Database Configuration Files in Java

Creating a Configuration File

First, create a configuration file named db.properties containing the database connection parameters in key-value format:

db.url=jdbc:mysql://localhost:3306/mydatabase
db.username=root
db.password=123456

Java Code Example

The following Java class reads this configuration file and establishes a database connection:

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

public class DatabaseConnector {
    public static void main(String[] args) {
        Properties props = new Properties();
        try (FileInputStream fis = new FileInputStream("db.properties")) {
            props.load(fis);
            
            String url = props.getProperty("db.url");
            String username = props.getProperty("db.username");
            String password = props.getProperty("db.password");
            
            try (Connection conn = DriverManager.getConnection(url, username, password)) {
                System.out.println("Connected to the database successfully!");
            }
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }
}

Code Walkthrough

  • The Properties object handles loading key-value pairs from the file.
  • getProperty() retrieves the specific configuration values: URL, username, and password.
  • DriverManager.getConnection() uses these values to open a database connection.
  • Both FileInputStream and Connection are closed automatically using try-with-resources.

Database URL Formats

Database URL Pattern
MySQL jdbc:mysql://localhost:3306/mydatabase
Oracle jdbc:oracle:thin:@localhost:1521:mydatabase

Connection Process

  1. Load configurasion file.
  2. Extract database parameters.
  3. Establish connection via JDBC driver.
  4. Handle any I/O or SQL exceptions.

Storing database credentials externally allows changing connection details without recompiling code, enhancing maintainability and security.

Tags: java database configuration Properties file JDBC

Posted on Mon, 31 Aug 2026 16:56:52 +0000 by Sikk Industries