SQL from Java

Updated · 15 min read
mediumPostgreSQL 18sqljavajdbcpreparedstatementtransactionsconnection-poolinterview

JDBC (Java Database Connectivity) is the standard Java library for sending SQL to a database and reading the results. Every Java program that talks to PostgreSQL, MySQL, SQL Server or Oracle uses it, either directly or through a framework built on top of it, such as Spring's JdbcTemplate or Hibernate. Your SQL doesn't change: JDBC simply carries it to the database and brings rows back as Java values. In this lesson, we will connect to the Fee Tracker, run a query with a PreparedStatement, read a ResultSet, handle NULL correctly, insert a row and get its new id, group two changes in a transaction, send many rows in one batch, and borrow connections from a pool. Every program here was run against the Fee Tracker, and the output shown is what it printed.

In One Minute

  • DriverManager.getConnection(url, user, password) opens a Connection.
  • A PreparedStatement holds SQL with ? placeholders; setInt, setString and friends fill them as values, never as SQL text.
  • executeQuery() returns a ResultSet; executeUpdate() returns the number of rows changed.
  • getInt returns 0 for NULL; use getObject(col, Integer.class) or wasNull().
  • setAutoCommit(false), then commit() or rollback(), makes several statements one transaction.
  • Close everything with try-with-resources, and use a connection pool in real applications.

Setting Up

To use JDBC with PostgreSQL, add the PostgreSQL JDBC driver to your project. With Maven, that's one dependency:

XML
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.7.5</version>
</dependency>

The driver finds the database from a JDBC URL: jdbc:postgresql://localhost:5432/feetracker means PostgreSQL on this computer, port 5432, database feetracker. MySQL URLs start with jdbc:mysql:// and SQL Server URLs with jdbc:sqlserver://; the rest of the code in this lesson stays the same. The password comes from an environment variable, never from the source code (Database Hosting). For a full tour of the JDBC classes, see JDBC in Java in the Java course.

Your First Query

A query in JDBC takes three objects: a Connection to the database, a PreparedStatement holding the SQL, and a ResultSet holding the rows that come back. This program lists every course that costs $300 or more:

Java
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class CourseList {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:postgresql://localhost:5432/feetracker";
        String user = "fee_app";
        String password = System.getenv("FEE_DB_PASSWORD");
 
        String sql = "SELECT title, fee_usd FROM courses"
                + " WHERE fee_usd >= ? ORDER BY fee_usd DESC, title";
 
        try (Connection conn =
                     DriverManager.getConnection(url, user, password);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setBigDecimal(1, new BigDecimal("300.00"));
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    String title = rs.getString("title");
                    BigDecimal fee = rs.getBigDecimal("fee_usd");
                    System.out.println(title + ": $" + fee);
                }
            }
        }
    }
}
Output
Java Collections: $550.00
Java OOP: $500.00
Java Basics: $450.00
JavaScript Basics: $450.00
SQL Basics: $400.00

Explanation: The SQL has a ? where the fee goes. ps.setBigDecimal(1, ...) fills placeholder number 1 (JDBC counts from 1, not 0). executeQuery() sends the SQL and the value separately, so the value can never change the meaning of the SQL (SQL Injection). The ResultSet starts before the first row; each rs.next() moves to the next row and returns false when there are no more. getString("title") and getBigDecimal("fee_usd") read columns by name. Money uses BigDecimal, because double can't hold amounts such as 0.10 exactly. The ORDER BY ends with title so the two $450 courses always come back in the same order.

The SQL by itself is an ordinary query. Here it is with the value written in, so you can run it in Try it and compare the rows with the program's output:

SQL▶ Try it
SELECT title, fee_usd
FROM courses
WHERE fee_usd >= 300
ORDER BY fee_usd DESC, title;
Output
       title       | fee_usd
-------------------+---------
 Java Collections  |  550.00
 Java OOP          |  500.00
 Java Basics       |  450.00
 JavaScript Basics |  450.00
 SQL Basics        |  400.00
(5 rows)

Try-with-resources (try (...) { }) closes the ResultSet, the PreparedStatement and the Connection automatically, in reverse order, even if an exception is thrown. A connection that isn't closed stays open on the server, and enough of them can use up max_connections (Troubleshooting a Database). See Try-With-Resources in Java.

Connection, PreparedStatement, ResultSet: opened in order, closed in reverse
SQL typeRead withJava type
INTEGERgetInt or getObject(col, Integer.class)int / Integer
NUMERIC(8,2)getBigDecimalBigDecimal
VARCHAR, TEXTgetStringString
DATEgetObject(col, LocalDate.class)LocalDate
TIMESTAMPTZgetObject(col, OffsetDateTime.class)OffsetDateTime
BOOLEANgetBooleanboolean

Reading NULL Safely

getInt, getLong, getDouble and getBoolean return 0 or false when the column is NULL, because Java's primitive types can't hold null. That quietly turns "unknown" into a real-looking number. Payment 5 is Srihitha's, with no method recorded, and she has no mentor; payment 6 is Navika's, and her mentor is student 102:

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class PaymentNulls {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:postgresql://localhost:5432/feetracker";
        String pw = System.getenv("FEE_DB_PASSWORD");
        String sql = "SELECT s.first_name, s.mentor_id, p.method"
                + " FROM students s JOIN payments p USING (student_id)"
                + " WHERE p.payment_id IN (5, 6) ORDER BY p.payment_id";
 
        try (Connection conn =
                     DriverManager.getConnection(url, "fee_app", pw);
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                // getString gives null for SQL NULL
                String method = rs.getString("method");
                // getInt gives 0 for SQL NULL, so check wasNull() right after
                int mentor = rs.getInt("mentor_id");
                boolean noMentor = rs.wasNull();
                // getObject with a class gives null for SQL NULL
                Integer mentorOrNull =
                        rs.getObject("mentor_id", Integer.class);
                System.out.println(rs.getString("first_name")
                        + " | method=" + method
                        + " | getInt=" + mentor + " wasNull=" + noMentor
                        + " | getObject=" + mentorOrNull);
            }
        }
    }
}
Output
Srihitha | method=null | getInt=0 wasNull=true | getObject=null
Navika | method=card | getInt=102 wasNull=false | getObject=102

Explanation: For Srihitha, getString correctly returns null for the missing method, but getInt("mentor_id") returns 0, as if her mentor were student 0. Only wasNull(), called right after the get, reveals that the value was NULL. getObject("mentor_id", Integer.class) is simpler: it returns an Integer that is null for NULL. For Navika, all three ways agree on 102.

getInt turns NULL into 0; getObject keeps it null

Inserting and Getting the New Id

executeUpdate() runs an INSERT, UPDATE or DELETE and returns how many rows it changed. To learn the id the database generated, name the key column when preparing the statement:

Java
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
 
public class AddPayment {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:postgresql://localhost:5432/feetracker";
        String pw = System.getenv("FEE_DB_PASSWORD");
        String sql = "INSERT INTO payments"
                + " (student_id, course_id, amount_usd,"
                + "  due_on, paid_on, method)"
                + " VALUES (?, ?, ?, ?, ?, ?)";
        String[] keyColumns = {"payment_id"};
 
        try (Connection conn =
                     DriverManager.getConnection(url, "fee_app", pw);
             PreparedStatement ps = conn.prepareStatement(sql, keyColumns)) {
            ps.setInt(1, 102);                        // Advitha
            ps.setInt(2, 4);                          // JavaScript Basics
            ps.setBigDecimal(3, new BigDecimal("200.00"));
            ps.setObject(4, LocalDate.of(2026, 1, 5));
            ps.setObject(5, LocalDate.of(2026, 1, 5));
            ps.setString(6, "card");
 
            int rows = ps.executeUpdate();
            try (ResultSet keys = ps.getGeneratedKeys()) {
                keys.next();
                System.out.println(rows + " row inserted, payment_id = "
                        + keys.getInt(1));
            }
        }
    }
}
Output
1 row inserted, payment_id = 8

Explanation: prepareStatement(sql, new String[] {"payment_id"}) asks the driver to return the payment_id column of the new row; the PostgreSQL driver does it by adding RETURNING payment_id to the INSERT. getGeneratedKeys() gives those values as a small ResultSet. Dates are sent with setObject and a LocalDate, which maps straight to SQL DATE. The Fee Tracker already had seven payments, so the new one is number 8.

Transactions

By default, JDBC commits every statement on its own (auto-commit). To make several statements succeed or fail together, turn auto-commit off, then call commit() or rollback(). Here, Advitha pays for two courses at once, and a bug sends a negative amount for the second one:

Java
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
 
public class PayTwoCourses {
    static final String URL = "jdbc:postgresql://localhost:5432/feetracker";
    static final String INSERT = "INSERT INTO payments"
            + " (student_id, course_id, amount_usd, due_on, paid_on, method)"
            + " VALUES (?, ?, ?, ?, ?, 'card')";
 
    static void pay(Connection conn, int studentId, int courseId,
                    String amount) throws SQLException {
        LocalDate today = LocalDate.of(2026, 1, 5);
        try (PreparedStatement ps = conn.prepareStatement(INSERT)) {
            ps.setInt(1, studentId);
            ps.setInt(2, courseId);
            ps.setBigDecimal(3, new BigDecimal(amount));
            ps.setObject(4, today);
            ps.setObject(5, today);
            ps.executeUpdate();
        }
    }
 
    static long countPayments(Connection conn, int studentId)
            throws SQLException {
        String sql = "SELECT count(*) FROM payments WHERE student_id = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, studentId);
            try (ResultSet rs = ps.executeQuery()) {
                rs.next();
                return rs.getLong(1);
            }
        }
    }
 
    public static void main(String[] args) throws SQLException {
        String pw = System.getenv("FEE_DB_PASSWORD");
        try (Connection conn =
                     DriverManager.getConnection(URL, "fee_app", pw)) {
            System.out.println("Advitha's payments before: "
                    + countPayments(conn, 102));
 
            conn.setAutoCommit(false);         // start a transaction
            try {
                pay(conn, 102, 1, "450.00");   // Java Basics: fine
                pay(conn, 102, 4, "-200.00");  // a bug: negative amount
                conn.commit();
            } catch (SQLException e) {
                conn.rollback();               // undo the first payment too
                String firstLine =
                        e.getMessage().lines().findFirst().orElse("");
                System.out.println("Rolled back: " + e.getSQLState()
                        + " " + firstLine);
            } finally {
                conn.setAutoCommit(true);
            }
 
            System.out.println("Advitha's payments after: "
                    + countPayments(conn, 102));
        }
    }
}
Output
Advitha's payments before: 0
Rolled back: 23514 ERROR: new row for relation "payments" violates check constraint "payments_amount_usd_check"
Advitha's payments after: 0

Explanation: The first INSERT succeeded inside the transaction. The second broke the CHECK (amount_usd > 0) constraint, so PostgreSQL raised an error that JDBC turned into a SQLException with SQLState 23514, the standard code for a check violation. The catch block called rollback(), which also undid the first payment: Advitha has 0 payments before and after. The finally block turns auto-commit back on, so the connection is left the way it was found; this matters when connections are reused from a pool.

One failure rolls back both payments
SQLStateMeaningTypical cause
23505Unique violationA duplicate key
23503Foreign key violationA payment for a student that doesn't exist
23514Check violationA negative amount
23502Not-null violationA required column left empty
40001Serialization failureRetry the transaction (Isolation Levels)
40P01Deadlock detectedRetry the transaction (Locks and Deadlocks)

Check getSQLState(), not the message text, to decide what to do: the message wording can change between versions and languages, while the five-character code is standard. See Transaction Management in JDBC for savepoints and isolation levels in JDBC.

Batches

A batch sends many executions of the same statement in one round trip. Inserting 1,000 rows one by one means 1,000 trips to the server; a batch sends them together:

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.Arrays;
 
public class BatchInsert {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:postgresql://localhost:5432/feetracker";
        String pw = System.getenv("FEE_DB_PASSWORD");
        String[][] sessions = {
            {"101", "2026-01-06", "Window functions"},
            {"102", "2026-01-06", "Promises"},
            {"103", "2026-01-07", "Joins"},
        };
        String insert = "INSERT INTO study_sessions"
                + " (student_id, studied_on, topic) VALUES (?, ?, ?)";
 
        try (Connection conn =
                     DriverManager.getConnection(url, "fee_app", pw)) {
            try (Statement st = conn.createStatement()) {
                st.execute("CREATE TABLE study_sessions ("
                        + " student_id INTEGER REFERENCES students,"
                        + " studied_on DATE NOT NULL, topic TEXT NOT NULL)");
            }
            conn.setAutoCommit(false);
            try (PreparedStatement ps = conn.prepareStatement(insert)) {
                for (String[] s : sessions) {
                    ps.setInt(1, Integer.parseInt(s[0]));
                    ps.setObject(2, LocalDate.parse(s[1]));
                    ps.setString(3, s[2]);
                    ps.addBatch();                  // queue it; nothing sent
                }
                int[] counts = ps.executeBatch();   // send all three at once
                conn.commit();
                System.out.println("Inserted per statement: "
                        + Arrays.toString(counts));
            }
        }
    }
}
Output
Inserted per statement: [1, 1, 1]

Explanation: addBatch() stores the current values without sending anything. executeBatch() sends all three and returns an array with the row count of each one. Wrapping the batch in a transaction means a failure part way through leaves no half-loaded data. With the PostgreSQL driver, adding reWriteBatchedInserts=true to the JDBC URL lets it combine the rows into multi-row INSERT statements, which is faster still. See Batch Processing in JDBC.

Connection Pools

Opening a database connection takes time (a network handshake, authentication and a new server process), so real applications borrow connections from a pool instead. HikariCP is the most widely used pool in Java, and the default in Spring Boot:

Java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class PooledLookup {
    // One pool for the whole application, created once at startup.
    static final HikariDataSource POOL = createPool();
 
    static HikariDataSource createPool() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:postgresql://localhost:5432/feetracker");
        config.setUsername("fee_app");
        config.setPassword(System.getenv("FEE_DB_PASSWORD"));
        config.setMaximumPoolSize(5);        // at most 5 connections
        config.setConnectionTimeout(3_000);  // wait up to 3 s for one
        return new HikariDataSource(config);
    }
 
    static String firstName(int studentId) throws SQLException {
        String sql = "SELECT first_name FROM students WHERE student_id = ?";
        // close() returns the connection to the pool; it stays open.
        try (Connection conn = POOL.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, studentId);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next() ? rs.getString(1) : null;
            }
        }
    }
 
    public static void main(String[] args) throws SQLException {
        for (int id : new int[] {101, 102, 103, 999}) {
            System.out.println(id + " -> " + firstName(id));
        }
        POOL.close();
    }
}
Output
101 -> Srihitha
102 -> Advitha
103 -> Navika
999 -> null

Explanation: The pool is created once, when the program starts. POOL.getConnection() hands out an open connection, and close() (called by try-with-resources) gives it back to the pool instead of disconnecting, so the next request reuses it. setMaximumPoolSize(5) caps how many connections this program may open; with many copies of an app running, those caps add up (Replication and Scaling). If all five are busy, getConnection() waits up to connectionTimeout, then throws an exception. Student 999 doesn't exist, so rs.next() is false and the method returns null. See Connection Pooling and DataSource in JDBC.

Common Mistakes

Building SQL with + and user input. It invites SQL injection. Always use ? placeholders.

Reading a nullable number with getInt. NULL becomes 0. Use getObject(col, Integer.class) or wasNull().

Forgetting to close connections. Leaked connections pile up until the server refuses new ones. Use try-with-resources.

Using double for money. Use BigDecimal and NUMERIC columns.

Leaving auto-commit off after a transaction. The next user of a pooled connection inherits it. Restore it in finally, or let the pool or framework manage transactions.

Matching on error messages. Use getSQLState() codes, which are standard.

Interview Corner

What is the difference between Statement and PreparedStatement?

A Statement sends SQL text exactly as built, so user input pasted into it can change the SQL. A PreparedStatement sends SQL with ? placeholders and the values separately, which prevents SQL injection, handles types and quoting, and lets the driver reuse the parsed statement.

How do you run two statements in one transaction with JDBC?

Call conn.setAutoCommit(false), run both statements, then conn.commit(). If either throws, call conn.rollback() in the catch, and restore auto-commit in finally.

Why does rs.getInt return 0 for a NULL column, and how do you avoid it?

int can't hold null, so JDBC returns 0. Call rs.wasNull() right after, or use rs.getObject(col, Integer.class), which returns null.

Why use a connection pool?

Opening connections is slow and each one uses server memory. A pool keeps a few open and lends them out, which speeds up requests and caps how many connections the app can open.

Practice

Challenge: Write a method List<String> unpaidStudents(Connection conn) that returns the first names of students with no payments, in alphabetical order. Use a PreparedStatement and try-with-resources.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
public class UnpaidStudents {
    static List<String> unpaidStudents(Connection conn) throws SQLException {
        String sql = "SELECT first_name FROM students s"
                + " WHERE NOT EXISTS (SELECT 1 FROM payments p"
                + "                   WHERE p.student_id = s.student_id)"
                + " ORDER BY first_name";
        List<String> names = new ArrayList<>();
        try (PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                names.add(rs.getString("first_name"));
            }
        }
        return names;
    }
 
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:postgresql://localhost:5432/feetracker";
        String pw = System.getenv("FEE_DB_PASSWORD");
        try (Connection conn =
                     DriverManager.getConnection(url, "fee_app", pw)) {
            System.out.println("Unpaid: " + unpaidStudents(conn));
        }
    }
}
Output
Unpaid: [Advitha]

NOT EXISTS finds students without a matching payment (EXISTS). Only Advitha has never paid. The method takes the Connection as a parameter, so the caller decides whether it comes from DriverManager or a pool, and closes it.

Quick check: SQL from Java

4 questions
1Which call sends a SELECT and returns rows?
2The mentor_id column is NULL. What does rs.getInt("mentor_id") return?
3In a transaction with auto-commit off, the second of two INSERTs fails and you call rollback(). What is saved?
4Which SQLState means a check constraint was violated?

Key Takeaways

You want toUse
Open a connectionDriverManager.getConnection(url, user, password) or dataSource.getConnection()
Run a query with a valueconn.prepareStatement("... WHERE x = ?"), ps.setInt(1, v), ps.executeQuery()
Change rowsps.executeUpdate() (returns the row count)
Get a generated idprepareStatement(sql, new String[] {"id"}), then getGeneratedKeys()
Read a nullable integerrs.getObject("col", Integer.class)
Group statementssetAutoCommit(false), commit(), rollback()
Insert many rowsaddBatch() and executeBatch()

Was this tutorial helpful?

Lesson 102 of 115