JDBC ·
‹ Previous
⏱ 5 min read Modified: 2026-11-22

JDBC. Practical Tasks

JDBC exercises on this page are 9 hands-on tasks for anyone who has finished the module on working with a database from Java: create a table and read it with Statement and ResultSet, insert rows in a batch with PreparedStatement, find and close a SQL injection, get the id of a new row with getGeneratedKeys, write a DAO, catch a connection leak in a HikariCP pool, and wrap a user registration in a single transaction with rollback and Savepoint.

The exercises go from simple to hard and all use one practice database, catalog, from the module lessons: the users table and the phones table that you create in the first exercise. Every exercise states the expected output, so you can check your result without a reference solution. The last exercise is part of the Online Store project: you connect the store’s database to your Java code.

What to Review Before You Start

Everything these exercises need is covered in the four lessons of the module «JDBC: Connecting Java to a Database». If an exercise does not work out, open the lesson from the table: the right column shows which exercises it belongs to.

Lesson What you will need Exercises
JDBC Drivers and Connecting Java to a Database The mysql-connector-j Maven dependency, the connection URL, the No suitable driver found and Access denied errors All of them: nothing runs without a connection
Statement, PreparedStatement and ResultSet in JDBC executeUpdate and executeQuery, reading a ResultSet, batch updates, ? parameters, SQL injection, getGeneratedKeys The phones table, reading, batch insert, safe search, user registration
DAO Pattern and HikariCP Connection Pool in JDBC The Dao interface, the UserDao class, database.properties, HikariCP, connection leaks PhoneDao, the connection leak, the Online Store
JDBC Transactions: setAutoCommit, commit and rollback setAutoCommit(false), commit, rollback, Savepoint, one transaction across several DAOs Registration in one transaction, the Online Store

Set Up Your Environment

You need MySQL 8, Java 11 or newer and a Maven project with the mysql-connector-j driver; the connection pool exercises also need HikariCP. First create the catalog database and the users table:

CREATE DATABASE IF NOT EXISTS catalog;
USE catalog;

CREATE TABLE IF NOT EXISTS users (
    id       INT NOT NULL AUTO_INCREMENT,
    username VARCHAR(50),
    PRIMARY KEY (id)
);

INSERT INTO users (username) VALUES ('sidorov'), ('petrov'), ('kozlov');

If you ran the examples from the lesson Statement, PreparedStatement and ResultSet in JDBC, the table already exists and its first three rows are the same: sidorov (id 1), petrov (2), kozlov (3). The expected outputs in the exercises are calculated for these three users.

Dependencies in pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>9.1.0</version>
</dependency>
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>6.3.0</version>
</dependency>

To see HikariCP leak warnings, also add org.slf4j:slf4j-simple. The starter code of the exercises takes the connection settings from a ConnectionData class, as in the lesson. Only the password is not written as a string here: it is read from an environment variable so that it does not end up in Git together with your code:

package jdbc;

public class ConnectionData {
    public static final String URL = "jdbc:mysql://localhost:3306/catalog";
    public static final String USER = "root";
    public static final String PASSWORD = System.getenv("DB_PASSWORD");
}

In IntelliJ IDEA, set the variable in Run → Edit Configurations → Environment variables: DB_PASSWORD=your_password. If you forget it, PASSWORD is null and MySQL answers Access denied for user 'root'@'localhost' (using password: NO) — the words using password: NO tell you that the password never reached the driver.

Create the phones Table with Statement

The practice table users already exists in the catalog database (see “Set Up Your Environment”). Below is a class that creates it. Change it so that it creates the table phones with these columns:

  • id — INT, AUTO_INCREMENT, PRIMARY KEY;
  • user_id — INT NOT NULL;
  • phone_number — VARCHAR(10) NOT NULL.

As an extra, add a foreign key user_id → users.id.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class CreatingTable {
    private static final String CREATE_TABLE_QUERY =
            "CREATE TABLE users "
                    + "(id INT NOT NULL AUTO_INCREMENT,"
                    + " username VARCHAR(50), "
                    + "PRIMARY KEY(id));";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement()) {
            statement.executeUpdate(CREATE_TABLE_QUERY);
            System.out.println("Table users created");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Check: on the first run the program prints Table phones created; on the second run it prints the MySQL message Table 'phones' already exists. To see the table structure, run DESCRIBE phones; in the mysql client.

If you run it many times

A repeated CREATE TABLE fails with a SQLException because the table already exists. For a practice script that you run again and again, write CREATE TABLE IF NOT EXISTS phones ...: instead of an error, MySQL records a note (Note 1050), and executeUpdate returns 0, as it does for any DDL command.

Read the phones Table with ResultSet

Add some test data to the phones table (in the mysql client or MySQL Workbench):

INSERT INTO phones (user_id, phone_number) VALUES
(1, '0501234567'), (1, '0671112233'), (2, '0939876543');

Below is a class that reads the users table. Change it so that it prints all rows of the table phones in id order: the columns id, user_id and phone_number.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class RetrieveData {
    private static final String SELECT_QUERY = "SELECT * FROM users;";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {

            System.out.printf("%-20s%s%n", "id", "username");
            System.out.println("-------------------------------");
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("username");
                System.out.printf("%-20d%s%n", id, name);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Expected output with the row format "%-6d%-10d%s%n":

id    user_id   phone_number
------------------------------
1     1         0501234567
2     1         0671112233
3     2         0939876543

The leading zero

A phone number is stored in a VARCHAR column, so read it with getString("phone_number"). The driver lets you read it with getInt too, but then 0501234567 becomes the number 501234567 and the leading zero is lost. Instead of SELECT *, list the columns explicitly: SELECT id, user_id, phone_number FROM phones ORDER BY id.

Batch Insert of Phones with PreparedStatement

Below is a class that adds users in a batch. Change it so that it writes three phone numbers of the user with id = 3 to the phones table in one batch: 0505556677, 0631234567, 0973332211. The query must have two parameters: INSERT INTO phones (user_id, phone_number) VALUES (?, ?).

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class InsertDataPreparedStatement {
    private static final String INSERT_QUERY =
            "INSERT INTO users (username) VALUES (?)";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement preparedStatement =
                     connection.prepareStatement(INSERT_QUERY)) {

            preparedStatement.setString(1, "misha");
            preparedStatement.addBatch();

            preparedStatement.setString(1, "grisha");
            preparedStatement.addBatch();
            int[] counts = preparedStatement.executeBatch();
            System.out.println(Arrays.toString(counts));
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Expected output: [1, 1, 1]. After that, the RetrieveData class from the previous exercise should show six rows, and the last three of them have user_id = 3.

If the foreign key is enabled

With the foreign key user_id → users.id, inserting a phone for a user that does not exist fails with Cannot add or update a child row: a foreign key constraint fails, and executeBatch() throws a BatchUpdateException. The rows inserted before the error stay in the table, because the connection is in autocommit mode. How to cancel the whole batch, you will find out in the transaction exercise.

The PhoneSearch class prints the phones of a user by user name. The query is built by string concatenation.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class PhoneSearch {
    static void printPhones(Connection connection, String username) throws SQLException {
        String query = "SELECT p.phone_number FROM phones p "
                + "JOIN users u ON u.id = p.user_id "
                + "WHERE u.username = '" + username + "' ORDER BY p.id";
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {
            while (resultSet.next()) {
                System.out.println(resultSet.getString("phone_number"));
            }
        }
    }

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
            printPhones(connection, "sidorov");
            System.out.println("---");
            printPhones(connection, "' OR '1'='1");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
  1. Run the program on the data from the previous exercises. The second call prints all six numbers from the table, although there is no user with such a name. Print the final query string and explain why the WHERE condition became true for every row.
  2. Rewrite printPhones with a PreparedStatement and a ? parameter. After the fix, the program must print:
    0501234567
    0671112233
    ---
  3. Add a method printPhonesByPrefix(Connection connection, String prefix) that prints the numbers starting with prefix, also through a PreparedStatement. For the prefix "05", the expected output is 0501234567 and 0505556677.

Where to put the %

Add the % sign to the value in Java: the query is ... WHERE phone_number LIKE ? and the call is setString(1, prefix + "%"). If you write LIKE '?%' in the query text, the question mark inside the quotes becomes an ordinary character, not a parameter, and setString(1, ...) throws a SQLException: Parameter index out of range (1 > number of parameters, which is 0).

User Registration: Getting the id with getGeneratedKeys

Write a UserRegistration class that adds a user together with the user’s phones.

  1. The method int createUser(Connection connection, String username) adds a row to users and returns the id assigned by the database. Use Statement.RETURN_GENERATED_KEYS and getGeneratedKeys(); SELECT MAX(id) is not acceptable.
  2. The method void addPhones(Connection connection, int userId, List<String> numbers) adds all the numbers to phones in one batch (addBatch / executeBatch).
  3. In main, register the user ivanov with the numbers 0661234567 and 0991234567, then print the user’s phones with a query that has a user_id parameter.

Expected output if users contained only the three rows from the environment setup:

User ivanov created, id = 4
0661234567
0991234567

If the table already had other rows, the id will be larger. What matters is that the phones are found by the id that createUser returned.

The name of the key column

Read the key by column number: keys.getInt(1). MySQL Connector/J returns the generated key in a column named GENERATED_KEY, not id, so keys.getInt("id") throws a SQLException with the message Column 'id' not found.

The PhoneDao Class: CRUD for the phones Table

Write a DAO for the phones table, modeled on the UserDao class from the lesson “DAO Pattern and HikariCP Connection Pool in JDBC”.

  1. Create a Phone class with the fields Integer id, int userId and String phoneNumber, constructors and a toString() method.
  2. Create a PhoneDao class that implements the Dao<Integer, Phone> interface from the lesson and receives a DataSource in its constructor. Either the driver’s MysqlDataSource or a HikariDataSource will do.
  3. Implement Optional<Phone> findById(Integer id), which finds a phone in the database by its id.
  4. Implement List<Phone> findAll(), which returns all phones from the database in id order.
  5. Implement Phone create(Phone phone), which adds a new phone to the database and sets the id assigned by the database on the object.
  6. Implement boolean update(Phone phone), which updates the owner and the number of an existing phone and returns true if a row was changed.
  7. Implement boolean delete(Integer id), which deletes a phone from the database by its id.
  8. Add an overload boolean delete(Phone phone) that deletes the given phone: it takes the id from the object and calls delete(Integer).
  9. Optional: List<Phone> findByUserId(int userId) — all phones of one user.

Check it in main: after create, the object has an id; findById(1000) returns Optional.empty; delete(1000) returns false; with the data from the previous exercises, findByUserId(1) returns two phones.

An ambiguous overload

With two methods, delete(Integer) and delete(Phone), the call phoneDao.delete(null) does not compile: null fits both types, and the compiler reports reference to delete is ambiguous. In production code this is rare, but interviewers like to ask about it. Do not swallow a SQLException inside the methods by printing it to the console; wrap it in a DaoException, as in the lesson.

Connection Leak in a HikariCP Pool

A method that counts the phones of a user was added to the PhoneDao from the previous exercise:

public int countByUserId(int userId) {
    try {
        Connection connection = dataSource.getConnection();
        try (PreparedStatement statement = connection.prepareStatement(
                "SELECT COUNT(*) FROM phones WHERE user_id = ?")) {
            statement.setInt(1, userId);
            try (ResultSet resultSet = statement.executeQuery()) {
                resultSet.next();
                return resultSet.getInt(1);
            }
        }
    } catch (SQLException e) {
        throw new DaoException("Could not count phones of user " + userId, e);
    }
}

The test program:

HikariConfig config = new HikariConfig();
config.setJdbcUrl(URL);
config.setUsername(USER);
config.setPassword(PASSWORD);
config.setMaximumPoolSize(2);
config.setConnectionTimeout(3000);
config.setLeakDetectionThreshold(2000);

try (HikariDataSource dataSource = new HikariDataSource(config)) {
    PhoneDao phoneDao = new PhoneDao(dataSource);
    for (int i = 1; i <= 3; i++) {
        System.out.println("Call " + i + ": " + phoneDao.countByUserId(1));
    }
    System.out.println("Active connections: "
            + dataSource.getHikariPoolMXBean().getActiveConnections());
}
  1. Run the program. The first two calls print Call 1: 2 and Call 2: 2; after about 3 seconds the third one fails with a DaoException whose cause is SQLTransientConnectionException ... request timed out with total=2, active=2. Find the line that keeps the connections from returning to the pool and explain why the pool thinks they are in use.
  2. Find the HikariCP leak warning (Connection leak detection triggered) in the log and make sure its stack trace points to countByUserId.
  3. Fix the method. After the fix, the program prints three lines Call N: 2 and Active connections: 0, no matter how many times the method is called.

The leak detection threshold

leakDetectionThreshold does not accept values below 2000 ms: HikariCP treats such a value as a configuration error and disables the check with a warning in the log. The leak warning itself is written through SLF4J, so without slf4j-simple or Logback in the project you will see only the exception, but not the place of the leak.

Registration in One Transaction: rollback and Savepoint

In the getGeneratedKeys exercise, the user and the user’s phones are saved by separate queries. If one number fails, the user stays in the database without phones. Fix this with a transaction.

  1. Call createUser and addPhones from that exercise unchanged for the user kuznetsov_test with the numbers 0501112233 and 050111223344 (the second one is longer than VARCHAR(10)). Make sure the program fails and the query SELECT * FROM users WHERE username = 'kuznetsov_test' still finds the user.
  2. Write a method void registerUser(Connection connection, String username, List<String> numbers) throws SQLException: turn off auto-commit, call createUser and addPhones, then commit(). On a SQLException, call rollback() and rethrow the exception, and in finally restore the previous autoCommit mode of the connection.
  3. Call registerUser for kuznetsov with the same numbers. Expected: a BatchUpdateException with a message like Data truncation: Data too long for column 'phone_number' at row 1, and neither the user kuznetsov nor the first number is in the tables.
  4. Optional: a method registerAll(Connection connection, Map<String, List<String>> users) that registers several users in one transaction. Set a Savepoint before each user; if that user’s registration fails, roll back to the savepoint and move on to the next user, and call commit() at the end. Use a LinkedHashMap so that the order is predictable. For smirnov (0671234567), kuznetsov (050111223344) and popov (0931234567), the database must keep smirnov and popov with their numbers.

Gaps in id

After a rollback, the id of popov is one larger than you expect: InnoDB does not give back the AUTO_INCREMENT values that were issued to a rolled-back insert. This is normal; do not rely on there being no gaps in id. MySQL 8 raises the Data too long error in strict mode (STRICT_TRANS_TABLES, enabled by default). If strict mode is off, the long number is silently truncated to 10 characters with a warning, and there is nothing to roll back.

Online Store: DAOs on a HikariCP Pool and an Order Transaction

Online Store · part 16 of 16 · ← part 15

In the previous part you designed the online store database in MySQL: tables for products, catalogs and users. Now connect your Java code to it.

  1. Add the mysql-connector-j and HikariCP dependencies to pom.xml. Move the URL, user name and password to database.properties in src/main/resources; do not commit the file with the real password to Git.
  2. Create one HikariDataSource for the whole application (for example, in a ConnectionPool class) and close it when the program exits.
  3. Create DAO classes for products, catalogs and users with the methods findAll, findById (returns an Optional), create (sets the id on the object through getGeneratedKeys), update and delete. Read and write the price as a BigDecimal: getBigDecimal / setBigDecimal.
  4. Replace the storage of products in collections and files with DAO calls: when the program starts, the product catalog is loaded from the database.
  5. Add a stock column to the products table (if it is not there yet) and tables for orders and order items. Write a placeOrder(userId, cart) method that, in one transaction, creates the order and its items and decreases the stock with a query like UPDATE ... SET stock = stock - ? WHERE id = ? AND stock >= ?. If this query changed 0 rows, there is not enough stock: call rollback() and tell the user that the order was not placed.

Check: place an order in which the quantity of one product is larger than its stock. Afterwards, the orders table must not contain a new row, and the stock of every product must stay the same.

One transaction across several DAOs

If every DAO method takes its own connection from the pool, creating the order and decreasing the stock end up in different transactions, and you cannot roll them back together. For placeOrder, open the connection in the service, turn off auto-commit and pass this Connection as a parameter to every DAO method that takes part in the order. The scheme is explained in the section One Transaction Across Several DAOs.

Check Your Code Before You Call It Done

A JDBC solution can work and still contain code that a reviewer will ask you to rewrite. Before you consider an exercise solved, go through the table: every row is a sign of outdated or dangerous code that is common in old tutorials and forum answers.

In the code What is wrong What to do
Class.forName("com.mysql.jdbc.Driver") An outdated class name; the driver prints a warning Delete the line: since JDBC 4.0 the driver registers itself
INT(5) in CREATE TABLE The display width does not limit the number and has been deprecated since MySQL 8.0.17 Write INT
catch (Exception e) It also swallows bugs in your own code, such as NullPointerException catch (SQLException e); in a DAO, wrap it in your own exception
"... WHERE username = '" + name + "'" SQL injection A ? parameter and setString
ResultSet or Connection outside try-with-resources The resource is not closed when an exception is thrown; in a pool, that is a connection leak Put every resource in try-with-resources
getInt("phone_number") A phone number is a string; the leading zero disappears getString("phone_number")

Check your code

When you write the programs, pay attention to the code style checklist.

Frequently Asked Questions

Which versions of MySQL, Java and the driver do the JDBC exercises need?

MySQL 8.0 or newer, Java 11 or newer (HikariCP 5.x and 6.x require it) and the com.mysql:mysql-connector-j driver, version 8.0.31 or newer. New versions are no longer published under the old artifact name mysql:mysql-connector-java. How to add the driver is shown in the section How to Add a JDBC Driver to a Project.

Can I solve these exercises on PostgreSQL or H2 instead of MySQL?

Yes: the JDBC code barely changes, only the URL and the driver do. The SQL details differ. PostgreSQL uses GENERATED ALWAYS AS IDENTITY instead of AUTO_INCREMENT, and a phone number that is too long in the transaction exercise fails with value too long for type character varying(10) instead of Data too long for column. H2 with MODE=MySQL in the URL understands MySQL syntax and is handy for testing DAOs.

How do I check that a transaction really rolled back?

Check from another connection: after the program finishes, run a SELECT on the tables in the mysql client or in Workbench. Inside the transaction itself, your own uncommitted changes are visible, so a SELECT through the same Connection before rollback() shows the new rows and proves nothing.

Why should my solutions not use catch (Exception e)?

Such a block catches not only database errors but also bugs in your own code: NullPointerException, IndexOutOfBoundsException. The program prints a message and keeps going as if nothing had happened. Catch SQLException, and inside a DAO wrap it in your own unchecked exception with the cause, like DaoException in the lesson DAO Pattern and HikariCP Connection Pool in JDBC.

What is asked about JDBC in interviews?

You are rarely asked to write a whole program. More often the questions are: why PreparedStatement is better than Statement and how a SQL injection works, how to get the id after an INSERT, why you need a connection pool and what close() does on a pooled connection, and what happens to your data without setAutoCommit(false). There is an exercise on this page for each of these, so your answer will rest on your own run rather than on a memorized phrase.

Comments

Please log in or register to have a possibility to add comment.