Java · Advanced & Ecosystem

JDBC

JDBC is Java’s standard API for talking to relational databases like MySQL, PostgreSQL and SQL Server.

Advanced 5 min Lesson 28 of 31Examples target Java 21 LTS (they also run on Java 25).
0/31 in Java
On this page · 5 min · Advanced

In simple words#

JDBC is the telephone line between Java and the database: open a connection, speak a prepared question (PreparedStatement), listen to the answers row by row (ResultSet), hang up.

Connection
Session with the database.
PreparedStatement
SQL with ? parameters — safe and fast.
ResultSet
Rows returned by a query.

Learning objectives#

  • Connect to a database
  • Query with PreparedStatement
  • Map ResultSet rows to records
  • Use transactions

Explanation#

Add the driver dependency (e.g. com.microsoft.sqlserver:mssql-jdbc, org.postgresql:postgresql).

Get a Connection from DriverManager or, in real apps, a connection pool (HikariCP).

PreparedStatement with ? placeholders prevents SQL injection and handles types correctly.

conn.setAutoCommit(false) + commit/rollback groups changes into a transaction. Use try-with-resources for everything.

Code example: Querying products safely#

JavaQuerying products safely Illustrative
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


record Product(int id, String name, double price) {}


public class ProductDao {
    private static final String URL =
        "jdbc:sqlserver://localhost:1433;databaseName=ShopDB;encrypt=true;trustServerCertificate=true";


    static List<Product> findCheaperThan(double maxPrice) throws SQLException {
        String sql = "SELECT Id, Name, Price FROM Products WHERE Price < ? ORDER BY Price";
        try (Connection conn = DriverManager.getConnection(URL, System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setDouble(1, maxPrice);
            try (ResultSet rs = ps.executeQuery()) {
                List<Product> list = new ArrayList<>();
                while (rs.next()) list.add(new Product(rs.getInt("Id"), rs.getString("Name"), rs.getDouble("Price")));
                return list;
            }
        }
    }


    public static void main(String[] args) throws SQLException {
        findCheaperThan(5000).forEach(System.out::println);
    }
}
Expected output
Product[id=2, name=Mouse, price=1400.0]
Product[id=3, name=Keyboard, price=2200.0]

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. Credentials come from environment variables.
  2. The ? placeholder is filled with setDouble.
  3. rs.next() moves through rows; columns map to a record.
  4. try-with-resources closes connection, statement and result set.

Real-world use case#

Lightweight services and batch jobs use JDBC (or JdbcTemplate) for fast, hand-written SQL.

Common mistakes#

String concatenation in SQL

"... WHERE name = '" + input + "'" invites SQL injection. Use PreparedStatement.

Opening a new connection per query in a server app

Use a connection pool such as HikariCP.

Best practices#

  • PreparedStatement always
  • Connection pool in apps
  • try-with-resources
  • Credentials from environment or vault

Remember this#

Connection → PreparedStatement → ResultSet.

? placeholders stop SQL injection.

Pool connections in real apps.

Practice exercise#

Your task: Insert a product with a PreparedStatement.

Show solution
Java Illustrative
try (var ps = conn.prepareStatement("INSERT INTO Products (Name, Price) VALUES (?, ?)")) {
    ps.setString(1, "Webcam");
    ps.setDouble(2, 3200);
    ps.executeUpdate();
}

Mini quiz#

JDBC quizMultiple choice Question 1 of 1

Which JDBC interface protects against SQL injection?

Score so far: 0/0

Want more? Practise all Java MCQs · Java interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.