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
Propertiesobject 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
FileInputStreamandConnectionare 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
- Load configurasion file.
- Extract database parameters.
- Establish connection via JDBC driver.
- Handle any I/O or SQL exceptions.
Storing database credentials externally allows changing connection details without recompiling code, enhancing maintainability and security.