Lesson 36: JDBC: Connecting Java to a Database

06 Aug 2026 1 min Swarnil Singhai

JDBC is the standard API for talking to relational databases from Java — every ORM (Hibernate, JPA) is built on top of it.

Real-time example

An order-processing service inserts a new order row and reads it back using plain JDBC before any ORM enters the picture.

String url = "jdbc:postgresql://localhost:5432/shop";
try (Connection conn = DriverManager.getConnection(url, "user", "pass");
     PreparedStatement ps = conn.prepareStatement(
         "INSERT INTO orders(customer, amount) VALUES (?, ?)")) {
    ps.setString(1, "Amit");
    ps.setDouble(2, 499.00);
    ps.executeUpdate();
}

What's happening

try-with-resources on the Connection and PreparedStatement guarantees both are closed even if executeUpdate throws.

Never build SQL by string-concatenating user input — PreparedStatement placeholders (?) prevent SQL injection.

Advertisement