Skip to lesson content
Web Technologies › Level 25
LEVEL 25 · JDBC

JDBC and Database Connectivity

Bind values, map results and resolve database operations deliberately.

☕ Java web🔑 Bound statements🔄 Transactions🧪 Lab + MCQs
01

Learning Objectives

Connect

Separate API, driver, data source and database.

Bind

Keep values separate from SQL structure.

Read

Map result rows and check update counts.

Transact

Explain commit, rollback and owned resources.

02

API, Driver and Database Have Different Jobs

Database access boundary
Application

Uses Java database interfaces.

JDBC driver

Communicates with the chosen database.

Database

Executes SQL and enforces constraints.

Java model

Receives checked application values.

This lesson adds frontend teaching files only. No backend database or credential is created by the patch.

03

DriverManager and DataSource

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

// dataSource is supplied by protected backend configuration.
try (Connection con = dataSource.getConnection()) {
    // Prepare and execute database work here.
}
04

Connection Ownership and Resource Lifetimes

Close owned resources
Connection

Owns the database session boundary.

Statement

Owns SQL execution resources.

Result set

Owns a row cursor/result resource.

Cleanup

Close result, statement, then connection.

05

Prepared Statements Bind Values

String sql = "SELECT learner_id, tokens FROM practice_tokens "
           + "WHERE learner_id = ?";
try (java.sql.PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setString(1, acceptedLearnerId);
    try (java.sql.ResultSet rs = ps.executeQuery()) {
        // Map accepted rows here.
    }
}
06

Choose the Execution Method

executeQuery is used when the statement produces a result set. executeUpdate returns an update count for relevant data-changing statements; an operation that changes no matching row can legitimately return zero. execute handles cases where the result kind needs to be inspected.

executeQuery

Read a ResultSet for a query.

executeUpdate

Inspect the affected-row count.

execute

Inspect the returned result kind.

Generated keys

Use the appropriate separate API.

int changed = debit.executeUpdate();
if (changed != 1) {
    throw new java.sql.SQLException("Debit was not accepted");
}
// Only then attempt the paired credit.
07

ResultSet Cursors and Row Mapping

try (java.sql.ResultSet rs = ps.executeQuery()) {
    while (rs.next()) {
        String id = rs.getString("learner_id");
        int tokens = rs.getInt("tokens");
        if (rs.wasNull()) {
            throw new java.sql.SQLException("Missing required tokens");
        }
        // Check id and tokens, then create an application value.
    }
}
08

Repository Boundaries and Schema Assumptions

Illustrative SQL schema assumptions:
practice_tokens(learner_id PRIMARY KEY, tokens NOT NULL)
tokens must remain non-negative

Application operation:
validate → acquire owned connection → debit → credit
→ commit/rollback → close → choose response
09

Auto-Commit and Partial Operations

One operation, different boundaries
Debit

Change the source tokens.

Auto-commit

Debit is already published.

Credit failure

The paired update does not finish.

Partial result

Earlier debit remains committed.

10

One Transaction: Commit or Roll Back

// Illustrative owned-connection transaction fragment.
// Inputs were validated; dataSource and statement helper are supplied.
try (java.sql.Connection con = dataSource.getConnection()) {
    con.setAutoCommit(false);
    try {
        // Execute debit and credit on THIS connection.
        // Require the expected affected-row count for each.
        performTransferStatements(con, fromId, toId, amount);
        con.commit();
    } catch (java.sql.SQLException | RuntimeException failure) {
        try {
            con.rollback();
        } catch (java.sql.SQLException rollbackFailure) {
            failure.addSuppressed(rollbackFailure);
        }
        throw failure;
    }
}
11

Conditional Updates and Count Checks

UPDATE practice_tokens
SET tokens = tokens - ?
WHERE learner_id = ? AND tokens >= ?

Debit bindings: 1 = amount, 2 = fromId, 3 = amount

UPDATE practice_tokens
SET tokens = tokens + ?
WHERE learner_id = ?

Credit bindings: 1 = amount, 2 = toId
12

Isolation, Savepoints and Concurrent Work

Atomicity

Treat paired statements as one accepted unit.

Isolation

Account for simultaneous database work.

Savepoint

A supported rollback position within a transaction.

Timeout/retry

Use driver/database-aware bounded policies.

The lab has no locks, threads, savepoints, deadlocks or retries. Those runtime behaviors remain separate integration checks.

13

Errors and Uncertain Outcomes

Invalid input

Reject before acquiring a connection.

Unavailable

No mock connection is opened.

Zero debit

Do not execute the credit.

Commit uncertainty

Verify/recover instead of blindly retrying.

14

Pools, Configuration and Deployment

Keep credentials on the backend
Frontend

Sends an allowed application request.

Controller/service

Validates and authorizes.

Repository

Owns JDBC operations.

Configured data source

Supplies backend connections.

This course patch does not modify the Render tracers or add a JDBC backend. Its resource counters are local model data only.

15

Test Logic and Real JDBC Separately

Success

Paired transfer preserves the operation’s token total.

Known failure

Manual mode retains the earlier committed snapshot.

Partial outcome

Auto-commit reveals the committed debit.

Integration

Check actual database state and resource behavior.

16

Premium Visualizer — An Accepted JDBC Transaction

Trace a fictional token transfer through validation, connection acquisition, bound debit/credit updates, commit and cleanup. This approved five-stage player explains one accepted manual transaction without running Java or SQL.

JDBC TRANSACTION TRACE
Step 1 of 5
STEP 01

Accept the transfer operation

Validate distinct learner IDs and a bounded canonical integer amount.

A → B · amount 3

What is happening?

Rejected input stops before connection acquisition.

17

Premium Interactive — Commit, Rollback and Partial Transfer

Idle. JavaScript model; no database is connected.

Current committed mock balances

Fixed statement structure and separate bindings

No accepted bindings yet.

Operation trace and mock cleanup

No operation yet.

Before, attempted working state and committed after

No transfer attempted.

Current run resource counts and affected rows

No resources opened.

Simulated response

No response yet.

Outcome summary · safe text

No result yet.
18

Debugging — Check Counts, State and Ownership

Bindings

Match every one-based placeholder and setter type.

Result cursor

Call next before reading; distinguish null from zero.

Transaction

Check the same connection owns both updates.

Resources

Resolve the operation and close owned resources.

19

Interview Questions — Flip to Explain

QUESTION

Is JDBC itself a database engine?

Click or press Enter to explain
ANSWER

No. JDBC defines Java database-access APIs; a driver communicates with the actual database.

QUESTION

Does every DataSource provide pooling?

Click or press Enter to explain
ANSWER

No. DataSource is an abstraction; the configured implementation and environment determine pooling behavior.

QUESTION

Why bind values in a prepared statement?

Click or press Enter to explain
ANSWER

To keep supplied values separate from fixed SQL structure. Validation and authorization remain necessary.

QUESTION

Can a question-mark parameter represent a table name?

Click or press Enter to explain
ANSWER

No. Bound values are not arbitrary SQL identifiers or syntax; dynamic structure needs an application-controlled choice.

QUESTION

Where is a new ResultSet cursor initially?

Click or press Enter to explain
ANSWER

Before the first row. Call next and verify a row exists before reading values.

QUESTION

Why inspect affected-row counts for both updates?

Click or press Enter to explain
ANSWER

A zero or unexpected count does not satisfy this paired-transfer contract; do not silently treat it as success.

QUESTION

Can rollback undo an earlier auto-committed debit?

Click or press Enter to explain
ANSWER

No. That statement has already committed; rolling back later work does not restore it.

QUESTION

Does a commit exception always prove nothing persisted?

Click or press Enter to explain
ANSWER

No. Some failures can leave the outcome uncertain; a real operation needs verification and recovery rules.

20

MCQ Practice — Explain JDBC Decisions

PRACTICE

1. What implements database-specific JDBC communication?

PRACTICE

2. Where should database credentials be configured?

PRACTICE

3. What is the first JDBC parameter index?

PRACTICE

4. Which method returns a ResultSet for an appropriate query?

PRACTICE

5. What can executeUpdate return for no matching row?

PRACTICE

6. What must occur before reading a ResultSet row?

PRACTICE

7. How can a primitive getter distinguish SQL NULL afterward?

PRACTICE

8. Which mode groups the paired updates in this lab?

PRACTICE

9. What happens on a known credit failure in manual mode?

PRACTICE

10. What happens on the same failure in auto-commit mode?

PRACTICE

11. What is a question-mark placeholder appropriate for?

PRACTICE

12. Do model cleanup counters prove a real connection pool is healthy?

21

Extra Practice — Predict Persisted State

Manual success

Reset, A → B, amount 3, manual/none. Expect A9/B7, 200 and committed outcome.

Manual rollback

Reset, A → B, 3, manual/credit error. Expect A12/B4, 500 and rolled-back outcome.

Partial auto-commit

Reset, A → B, 3, auto/credit error. Expect A9/B4, 500 and partial debit.

Zero credit

Repeat with creditZero. Manual retains A12/B4; auto leaves A9/B4. Both reject the count.

Insufficient source

Reset, B → A, amount 5. Expect 409, zero debit rows, no credit statement and unchanged tokens.

Invalid input

Try 03, 3.0, spaces, 0, same source/destination or repeated amount shape. Expect 400, zero resources opened.

Unavailable fixture

Choose offline with valid input. Expect 503, unchanged balances and zero opened resources.

Repeated runs

Two successful A → B transfers of 3 produce A6/B10. Reset restores A12/B4, counters and outputs.

22

Quick Revision

Driver: Database-specific JDBC implementation.
DataSource: Configured connection factory.
Prepared statement: Fixed SQL plus bound values.
ResultSet: Advance cursor before reading.
Update count: Check the operation’s expected effect.
Auto-commit: Separate statements can leave partial work.
Transaction: Resolve paired work on one connection.
Rollback: Handle known failures before commit.
Ownership: Close the resources you own.
Integration: Verify real database and driver behavior.
23

Glossary — Flip to Learn

TERM

JDBC

Click to see meaning
DEFINITION

JDBC

Java APIs for connecting to databases and executing database operations.

TERM

JDBC driver

Click to see meaning
DEFINITION

JDBC driver

An implementation that communicates with a particular database.

TERM

DataSource

Click to see meaning
DEFINITION

DataSource

A configured connection-factory abstraction.

TERM

Connection

Click to see meaning
DEFINITION

Connection

A database session used for statements and transaction control.

TERM

PreparedStatement

Click to see meaning
DEFINITION

PreparedStatement

A statement with fixed SQL structure and separately bound parameter values.

TERM

ResultSet

Click to see meaning
DEFINITION

ResultSet

A cursor-based result object returned by a query.

TERM

Affected-row count

Click to see meaning
DEFINITION

Affected-row count

A result indicating how many rows an update operation affected.

TERM

Auto-commit

Click to see meaning
DEFINITION

Auto-commit

A mode in which each completed statement commits its transaction.

TERM

Rollback

Click to see meaning
DEFINITION

Rollback

An attempt to undo uncommitted work in the current transaction.

TERM

Transaction isolation

Click to see meaning
DEFINITION

Transaction isolation

Rules governing visibility of concurrent database work.

24

Final Challenge — Specify an Owned JDBC Operation

25

Level 25 Complete?

Explain driver/API/data-source roles, prepared bindings, result cursors and update counts. Reproduce a committed transfer, known rollback and partial auto-commit outcome; identify the real database checks this lab cannot perform. Completion is a local study marker.