Practice: JDBC section review
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most JDBC bugs found in code reviews are the same four: SQL built from user text, connections that are never closed, a transaction split across connections or missing its rollback, and rules sitting in the wrong layer. Each has a short, standard fix, and interviewers expect you to name it at once.
Code review 1: SQL built from user input
In Example 1 a product search becomes a UNION that prints every customer's email and phone: a real data leak from one search box. Example 2 is the fix.
Example 1 · SQL injection in a product search
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class InjectionDemo { // BAD: the user's text becomes part of the SQL static void search(Connection c, String text) throws SQLException { String sql = "SELECT sku, name FROM products WHERE name LIKE '%" + text + "%'"; System.out.println("Search for: " + text); try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { System.out.println(" " + rs.getString(1) + " | " + rs.getString(2)); } } }
public static void main(String[] args) throws SQLException { try (Connection c = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { search(c, "Clean"); search(c, "zzz' UNION SELECT email, phone FROM customers -- "); } }}Search for: Clean BK-CLEAN | Clean Code Search for: zzz' UNION SELECT email, phone FROM customers -- asha.rao@example.com | 9876543201 ravi.kumar@example.com | 9876543202 meena.iyer@example.com | null kabir.singh@example.com | 9876543204 priya.sharma@example.com | 9876543205 arjun.mehta@example.com | null divya.nair@example.com | 9876543207 imran.khan@example.com | 9876543208
What this code does
- The second search closes the quote, adds
UNION SELECT email, phone FROM customersand turns the rest of the line into a comment with--. - MySQL runs the changed query, so a product search prints every customer's email and mobile number.
Example 2 · The same search with a PreparedStatement
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class SafeSearchDemo { // GOOD: the SQL text is fixed; the user's text only ever fills the ? as a value static void search(Connection c, String text) throws SQLException { String sql = "SELECT sku, name FROM products WHERE name LIKE ?"; String pattern = "%" + text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"; System.out.println("Search for: " + text); try (PreparedStatement ps = c.prepareStatement(sql)) { ps.setString(1, pattern); try (ResultSet rs = ps.executeQuery()) { int rows = 0; while (rs.next()) { System.out.println(" " + rs.getString(1) + " | " + rs.getString(2)); rows++; } System.out.println(" rows: " + rows); } } }
public static void main(String[] args) throws SQLException { try (Connection c = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { search(c, "Clean"); search(c, "zzz' UNION SELECT email, phone FROM customers -- "); } }}Search for: Clean BK-CLEAN | Clean Code rows: 1 Search for: zzz' UNION SELECT email, phone FROM customers -- rows: 0
What this code does
- The SQL is always
... WHERE name LIKE ?; the attack text is only a value, so MySQL looks for a product whose name contains it and finds none. - The
replacecalls escape\,%and_so the user's text matches only itself insideLIKE.
SQL injection happens when text typed by a user is glued into the SQL string, so the user can change the query itself instead of only giving a value. The fix is a PreparedStatement with ? placeholders: the SQL text is fixed and sent to MySQL first, and the user's text is bound with setString and only ever counts as a value, quotes and all. For LIKE, also escape %, _ and \ inside the value, or a search for _ matches everything.
In a review, look for + next to SQL text and for createStatement(). One exception: names such as a sort column cannot be a ?; pick them from a fixed allow-list in code, never from the user's text.
Predict the output
Predict the injected query
The text comes from a search box. What does this query do once the text is glued in?
Code review 2: connections that are never closed
Example 3 borrows connections without closing them from a pool of 2: the third call waits, then fails. The closed version runs five queries on the same pool.
Example 3 · A leak that exhausts a pool of 2
Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database
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 LeakDemo { static HikariDataSource pool() { HikariConfig config = new HikariConfig(); config.setJdbcUrl(System.getenv("DB_URL")); config.setUsername(System.getenv("DB_USER")); config.setPassword(System.getenv("DB_PASSWORD")); config.setPoolName("demo-pool"); config.setMaximumPoolSize(2); config.setConnectionTimeout(2000); // wait at most 2 s for a free connection return new HikariDataSource(config); }
// BAD: the connection is never closed, so it never goes back to the pool static int countProductsLeaky(HikariDataSource ds) throws SQLException { Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement("SELECT COUNT(*) FROM products"); ResultSet rs = ps.executeQuery(); rs.next(); return rs.getInt(1); }
// GOOD: try-with-resources closes all three, even when a query fails static int countProducts(HikariDataSource ds) throws SQLException { try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement("SELECT COUNT(*) FROM products"); ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt(1); } }
public static void main(String[] args) { try (HikariDataSource ds = pool()) { for (int i = 1; i <= 3; i++) { System.out.println("Leaky call " + i + ": " + countProductsLeaky(ds) + " products"); } } catch (SQLException e) { System.out.println("Failed: " + e.getMessage()); } try (HikariDataSource ds = pool()) { for (int i = 1; i <= 5; i++) { countProducts(ds); } System.out.println("Closed calls: 5 queries on a pool of 2, no problem"); } catch (SQLException e) { System.out.println("Failed: " + e.getMessage()); } }}Leaky call 1: 15 products Leaky call 2: 15 products Failed: demo-pool - Connection is not available, request timed out after 2053ms (total=2, active=2, idle=0, waiting=0) Closed calls: 5 queries on a pool of 2, no problem
What this code does
- Each leaky call keeps one connection forever; the third call waits 2 seconds for a free one and gets
SQLTransientConnectionException(total=2, active=2, idle=0). - The closed version runs 5 queries on the same small pool, because each connection goes back to the pool when try-with-resources closes it. Your timing number will differ.
A connection leak is a connection borrowed and never closed. With a pool it never goes back, so after a few calls every connection is busy and the next getConnection() fails with Connection is not available, request timed out. The app works in a short test and dies after an hour in use.
The fix is try-with-resources around the Connection, the PreparedStatement and the ResultSet, so all three close in reverse order even when a query throws. In a review, any getConnection(), prepareStatement() or executeQuery() outside a try (...) header is a bug unless it is handed to code that closes it. HikariCP can help you find leaks: leakDetectionThreshold (ShopLite uses 10 seconds) logs a warning with the stack trace of any connection held longer than that.
Find the bug
Find the leaking line
Each method borrows from the pool. Find the line that leaks a connection.
This method counts the products.
Round 1 of 2Code review 3: a transaction split across connections
Example 4 inserts an order on one connection and its item on another. The item fails, and the order stays behind with no items.
Example 4 · Two connections leave half an order behind
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class TwoConnectionsDemo { static Connection open() throws SQLException { return DriverManager.getConnection(System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
static int insertOrder(Connection c) throws SQLException { String sql = "INSERT INTO orders (customer_id, address_id) VALUES (1, 1)"; try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { ps.executeUpdate(); try (ResultSet keys = ps.getGeneratedKeys()) { keys.next(); return keys.getInt(1); } } }
static void insertItem(Connection c, int orderId, int productId) throws SQLException { String sql = "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, 1, 499.00)"; try (PreparedStatement ps = c.prepareStatement(sql)) { ps.setInt(1, orderId); ps.setInt(2, productId); ps.executeUpdate(); } }
static int countOrders() throws SQLException { try (Connection c = open(); Statement st = c.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) { rs.next(); return rs.getInt(1); } }
// BAD: each step opens its own connection in auto-commit mode static void placeWithTwoConnections() throws SQLException { int orderId; try (Connection c = open()) { orderId = insertOrder(c); // committed at once } try (Connection c = open()) { insertItem(c, orderId, 999); // no product 999: fails } }
static void placeInOneTransaction() throws SQLException { try (Connection c = open()) { c.setAutoCommit(false); try { int orderId = insertOrder(c); insertItem(c, orderId, 999); c.commit(); } catch (SQLException | RuntimeException e) { c.rollback(); throw e; } } }
public static void main(String[] args) throws SQLException { System.out.println("Orders before: " + countOrders()); try { placeWithTwoConnections(); } catch (SQLException e) { System.out.println("Two connections failed: error " + e.getErrorCode()); } System.out.println("Orders now: " + countOrders() + " (an order with no items was left behind)"); try { placeInOneTransaction(); } catch (SQLException e) { System.out.println("One transaction failed: error " + e.getErrorCode() + ", rolled back"); } System.out.println("Orders now: " + countOrders()); try (Connection c = open(); Statement st = c.createStatement()) { st.executeUpdate("DELETE FROM orders WHERE order_id NOT IN (SELECT order_id FROM order_items)"); } }}Orders before: 16 Two connections failed: error 1452 Orders now: 17 (an order with no items was left behind) One transaction failed: error 1452, rolled back Orders now: 17
What this code does
- With two connections the order insert is committed before the item insert fails with error 1452 (no product 999), so the order count goes from 16 to 17.
- With one connection and auto-commit off, the same failure is rolled back and the count stays 17; the last statement removes the orphan order again. Your counts depend on your data.
A transaction only covers statements that run on the same connection with auto-commit off. On two connections each insert commits by itself. The fix has three parts: one connection for the whole unit of work, setAutoCommit(false), and commit() at the end with rollback() in a catch that catches every exception (not only SQLException) and rethrows it. In ShopLite, Database.inTransaction does this once, and services decide where a transaction starts.
The same review also checks layers: a DAO that commits, prints, or decides a rule such as "stock must not go below 0" has logic in the wrong place. Rules and transaction boundaries belong to the service; the DAO only runs SQL and translates SQLException.
Order of execution
Order the transaction
Tap the steps of saving an order and its items in one transaction, in order.
Report queries mapped into DTOs
Example 5 maps a sales-by-state report straight into a StateSales record, so the caller gets a list and never touches the ResultSet.
Example 5 · Sales by state mapped into a DTO
Runs in: a Maven project with the MySQL driver and the ShopLite database
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.util.ArrayList;import java.util.List;
// A DTO: exactly the fields this report needs, not a copy of any one tablerecord StateSales(String state, int orders, BigDecimal revenue) {}
public class StateSalesDemo { static final String SQL = """ SELECT a.state, COUNT(DISTINCT o.order_id) AS orders, SUM(oi.quantity * oi.unit_price) AS revenue FROM orders o JOIN addresses a ON a.address_id = o.address_id JOIN order_items oi ON oi.order_id = o.order_id WHERE o.status <> 'CANCELLED' GROUP BY a.state ORDER BY revenue DESC""";
static List<StateSales> salesByState(Connection c) throws SQLException { try (PreparedStatement ps = c.prepareStatement(SQL); ResultSet rs = ps.executeQuery()) { List<StateSales> rows = new ArrayList<>(); while (rs.next()) { rows.add(new StateSales(rs.getString("state"), rs.getInt("orders"), rs.getBigDecimal("revenue"))); } return rows; } }
public static void main(String[] args) throws SQLException { try (Connection c = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { for (StateSales s : salesByState(c)) { System.out.printf("%-12s %2d orders Rs. %10s%n", s.state(), s.orders(), s.revenue()); } } }}Maharashtra 3 orders Rs. 113176.00 Delhi 2 orders Rs. 92098.00 Karnataka 3 orders Rs. 69334.00 Tamil Nadu 4 orders Rs. 25142.00 Kerala 2 orders Rs. 5893.00
What this code does
- The query joins orders to the delivery address and the items, groups by state and skips cancelled orders;
COUNT(DISTINCT o.order_id)counts orders, not items. - Each row becomes one
StateSalesrecord, so the caller gets aList<StateSales>and never touches theResultSet.
A DTO (Data Transfer Object) is a small record that carries exactly what one screen or report needs, such as StateSales(state, orders, revenue). Report queries join and group several tables, so their rows match no single entity; mapping them straight into a DTO keeps ResultSet code inside the DAO.
Three details make report SQL correct. Count orders with COUNT(DISTINCT o.order_id), because joining items repeats each order once per item. Leave cancelled orders out with WHERE o.status <> 'CANCELLED'. Read money with getBigDecimal, never getDouble. In an interview, the short version is: entities mirror tables and are used for changes; DTOs are shaped for reading and are what screens or APIs receive.
Finish up
Mark complete & continue
Next: Milestone project: sales reports and release on GitHub