Database Connectivity in Java: JDBC Transactions with a Worked Transfer

Follow one JDBC money transfer from connection setup to verified update counts, commit, query, forced failure and rollback, with exact balance calculations.

KnowledgeGate Team

Exam prep & CS education

Updated 21 Nov 20266 min read
Database Connectivity in Java: JDBC Transactions with a Worked Transfer

A short JDBC program can look like only "open, query, close", but its result crosses four boundaries: the Java API, the driver, the database session and the transaction; memorising methods is not enough if you confuse a connection with a successful transaction, concatenate input, or read a ResultSet before moving its cursor. JDBC in Java Tutorial: Connections, Queries and Transactions with Examples owns runnable H2 setup, connection and query mechanics, and a single guarded inventory update; a two-account transfer adds the harder requirement that debit and credit commit together. Moving 250.00 from Asha's account 101 to Ravi's 202 produces update counts 1 and 1, balances 1250.00 and 950.00, and a forced failure after the debit shows that rollback preserves the total 2200.00. The Coding & Skill Development Courses page places JDBC in the broader programming path.

JDBC is the contract between Java code and a database

The path is Java application -> JDBC API -> JDBC driver -> DBMS. JDBC supplies interfaces, the driver handles the protocol, and the DBMS runs SQL against stored data. A connection proves that a session exists, not that later work will succeed.

JDBC type

Role

Exact use in the worked transfer

DataSource

Obtains a Connection

Get connection C1

Connection

Owns session and transaction controls

Set auto-commit false, commit or rollback

PreparedStatement

Holds fixed SQL plus bound values

Debit 250.00 from account 101

ResultSet

Exposes query rows through a cursor

Read balances in account ID order

SQLException

Carries database-access failure information

Trigger rollback and preserve the original exception

Statement accepts SQL text, PreparedStatement fixes the SQL shape and binds values, and CallableStatement calls stored procedures. Here, 250.00, 101 and 202 are values. Placeholders cannot represent identifiers.

Four-layer JDBC path from the Java transfer service through the driver to the accounts table, with update counts of 1 for both statements.

Fix the schema, rows and transaction invariant

Use accounts(account_id INTEGER PRIMARY KEY, holder VARCHAR(40) NOT NULL, balance DECIMAL(10,2) NOT NULL CHECK (balance >= 0)). This assumes a transactional engine; DDL support varies by DBMS. Represent the amount as new BigDecimal("250.00"), not binary floating point.

Initially, 101, Asha, 1500.00 and 202, Ravi, 700.00 give 1500.00 + 700.00 = 2200.00. A transfer may redistribute that total, never change it.

The debit template is UPDATE accounts SET balance = balance - ? WHERE account_id = ? AND balance >= ?, bound as (250.00, 101, 250.00). The credit template is UPDATE accounts SET balance = balance + ? WHERE account_id = ?, bound as (250.00, 202). These are ordinary SQL queries applied to invented teaching rows.

Open and close JDBC resources deliberately

Nest try-with-resources: outer Connection con = dataSource.getConnection(), inner debit and credit statements, then a check statement and ResultSet. Resources close even on failure, but closure does not choose commit or rollback. DataSource configuration determines what close() does physically.

Save boolean previousAutoCommit = con.getAutoCommit(), call con.setAutoCommit(false), and restore the saved value in finally only once the transaction has actually been resolved. Restoring it is not neutral cleanup: JDBC commits any open transaction the moment auto-commit is switched back on, so a restore after a failed rollback can commit the half-finished transfer. If rollback itself fails, leave auto-commit unchanged; the connection must be discarded rather than returned to a pool for reuse.

Prepare SELECT account_id, holder, balance FROM accounts WHERE account_id IN (?, ?) ORDER BY account_id, bind 101 and 202, then call rs.next() before reading. The cursor starts before row one. Expect 101, Asha, 1250.00 and 202, Ravi, 950.00.

Worked transfer: account for every state change

This compact transaction validates both intended changes before committing:

java
BigDecimal amount = new BigDecimal("250.00");
int fromId = 101, toId = 202;

try (Connection con = dataSource.getConnection()) {
    boolean previousAutoCommit = con.getAutoCommit();
    con.setAutoCommit(false);
    boolean resolved = false;
    SQLException pending = null;
    try (PreparedStatement debit = con.prepareStatement(DEBIT_SQL);
         PreparedStatement credit = con.prepareStatement(CREDIT_SQL)) {
        debit.setBigDecimal(1, amount);
        debit.setInt(2, fromId);
        debit.setBigDecimal(3, amount);
        int debitCount = debit.executeUpdate();
        if (debitCount != 1) throw new SQLException("Debit changed " + debitCount + " rows");

        credit.setBigDecimal(1, amount);
        credit.setInt(2, toId);
        int creditCount = credit.executeUpdate();
        if (creditCount != 1) throw new SQLException("Credit changed " + creditCount + " rows");

        con.commit();
        resolved = true;
    } catch (SQLException ex) {
        pending = ex;
        try {
            con.rollback();
            resolved = true;
        } catch (SQLException rollbackEx) {
            ex.addSuppressed(rollbackEx);
        }
        throw ex;
    } finally {
        if (resolved) {
            try {
                con.setAutoCommit(previousAutoCommit);
            } catch (SQLException restoreEx) {
                if (pending != null) pending.addSuppressed(restoreEx);
                else throw restoreEx;
            }
        }
    }
}

Debit: 1500.00 - 250.00 = 1250.00, count 1. Credit: 700.00 + 250.00 = 950.00, count 1. Then 1250.00 + 950.00 = 2200.00, unchanged. Count 0 forbids commit. A rollback error is attached without losing the original cause. The resolved flag keeps the finally block honest: it is set only after commit or rollback succeeds, so a rollback failure never triggers an auto-commit restore. That prevents an accidental commit caused by the restore, but it does not prove that close() rolled back: a connection pool must discard or reset the failed connection according to its error policy. The same guard prevents a restore failure from masking the original exception. Never log passwords or full connection strings.

Success and failure timelines: commit leaves 101 at 1250.00 and 202 at 950.00, while a credit count of 0 forces a rollback.

Trace the rollback path

Start again from 101=1250.00 and 202=950.00. Sending 300.00 to missing account 999 tentatively gives 1250.00 - 300.00 = 950.00, debit count 1, but credit count 0. The deliberate SQLException triggers rollback. Account 101 returns to 1250.00, 202 stays 950.00, 999 remains absent, and 1250.00 + 950.00 = 2200.00 stays committed. With auto-commit on, the debit could survive alone.

A debit of 1400.00 from balance 1250.00 matches zero rows because of balance >= ?, so no credit runs. Do not pre-read and then issue an unconditional debit. The conditional update makes one statement decide, although locking and isolation depend on the DBMS and configured level.

Prevent common JDBC defects

Mistake

Consequence

Repair

Concatenate account input into SQL

Input can alter SQL structure

Bind values

Use double for 250.00

Binary rounding can affect money arithmetic

Use BigDecimal

Leave auto-commit on

Debit and credit become separate commits

Disable it for the unit of work

Ignore update count

A missing account looks successful

Require exactly one changed row

Read ResultSet before next()

Cursor is before the first row

Advance and test

Suppress SQLException

Caller sees false success

Roll back and rethrow

Binding separates values from SQL text. Dynamic identifiers and optional clauses need controlled construction, and binding cannot fix every injection or authorisation defect. Open late, finish one transaction, restore state, close deterministically, and load credentials from configuration. Measure pool sizes, timeouts and performance in the real system.

Test understanding through causality

Typical checks ask you to arrange the lifecycle, match JDBC types to roles, choose executeQuery() for row-producing SQL or executeUpdate() for an update, predict counts, trace commit and rollback, identify cursor position, spot concatenation, or calculate final rows.

Check: (1) starting total, (2) debit count, (3) balances after commit, (4) credit count for missing 999, (5) balance of 101 after rollback. Answers: (1) 2200.00; (2) 1; (3) 1250.00 and 950.00; (4) 0; (5) 1250.00. ResultSet reads rows; Connection controls this transaction. A connection can succeed while a statement fails, and resources can close after rollback.

The short version and the next step

Retrieve seven steps: obtain a connection; disable auto-commit; prepare fixed SQL; bind typed values; execute and validate both counts; commit on complete success or rollback; restore state and close. The arithmetic is 1500.00 - 250.00 = 1250.00, 700.00 + 250.00 = 950.00, total 2200.00.

Now restart from 1500.00 and 700.00, then transfer 425.50. You should get debit 1074.50, credit 1125.50, counts 1 and 1, and total 2200.00. Change the target to 999 and explain why rollback restores 1500.00 and 700.00.

Redraw both diagrams, implement that variation with BigDecimal, and test success, missing-target and insufficient-funds paths. Use Complete Java to build the wider foundation, or Java: Concepts, MCQs & Coding Questions when you want concept and question practice together.