Nearby lessons

24 of 37

JDBC - The Properties File

📌 What You Will Learn
  • Why creating a new connection every time is expensive
  • What connection pooling is and how it solves the problem
  • The modern DataSource approach
  • Keeping database settings in a Properties file

The Properties File is a fundamental part of database programming with JDBC. This lesson explains The Properties File — Keeping Settings Outside the Code with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The Properties File — Keeping Settings Outside the Code

Hard-coding the URL, username and password inside every program is bad practice. Better: keep them in a properties file (a simple key=value file) and load it with the Properties class.

Example01
JCode Cell
1# db.properties
2jdbc.driver=com.mysql.cj.jdbc.Driver
3jdbc.url=jdbc:mysql://localhost:3306/company
4jdbc.username=root
5jdbc.password=password

The Properties File — Keeping Settings Outside the Code

Why bother? If the database password changes, you edit one small file — you never touch or recompile your Java code. This is the professional habit.

In simple words: A properties file keeps the database settings outside your Java code. When the password changes you edit the file and rerun — no code changes and no recompilation.
Trainer's Note: One security tip: never commit a db.properties file with real passwords to a public repository. Keep real passwords in environment variables or a secrets manager; the properties file is perfect for local learning and configuration.
Example02
JCode Cell
1import java.util.*;
2import java.io.*;
3import java.sql.*;
4 
5public class PropertiesDemo {
6 public static void main(String[] args) throws Exception {
7 // 1. Load the properties file
8 Properties props = new Properties();
9 props.load(new FileInputStream("db.properties"));
10 
11 // 2. Read the settings
12 String url = props.getProperty("jdbc.url");
13 String user = props.getProperty("jdbc.username");
14 String pwd = props.getProperty("jdbc.password");
15 
16 // 3. Use them - no hard-coded values in the code!
17 Connection con = DriverManager.getConnection(url, user, pwd);
18 System.out.println("Connected using properties file");
19 con.close();
20 }
21}
Output
Connected using properties file
📝 Key Takeaways
  • Creating a connection each time is slow; pooling reuses ready connections.
  • Pool = borrow a connection, use it, return it — never destroy it.
  • DataSource is the modern replacement for DriverManager, often backed by a pool.
  • Properties file keeps DB settings outside the code; edit it without recompiling.
  • Use Properties.load() + getProperty() to read settings.
  • Keep real passwords out of public repos.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3