Practice: resources and SQL errors
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most JDBC resource and error bugs repeat the same four mistakes. Spotting them in real code is the fastest way to stop writing them.
Mistake 1: cleanup only on the happy path
The happy path is the run of a program in which nothing goes wrong. Cleanup written as the last lines of a method runs only on that path.
Close calls written as the last lines of a method run only on the happy path. Example 1 leaks a connection only when the SKU is unknown, then counts what stays open.
Example 1 · Mistake: a leak only when the SKU is unknown
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 ErrorPathLeakDemo { static final String URL = System.getenv("DB_URL"); static final String USER = System.getenv("DB_USER"); static final String PASSWORD = System.getenv("DB_PASSWORD"); static final String SQL = "SELECT stock FROM products WHERE sku = ?";
// BUG: the close calls run only when nothing goes wrong static int stockOfLeaky(String sku) throws SQLException { Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement ps = conn.prepareStatement(SQL); ps.setString(1, sku); ResultSet rs = ps.executeQuery(); if (!rs.next()) { throw new IllegalArgumentException("Unknown SKU " + sku); } int stock = rs.getInt("stock"); rs.close(); ps.close(); conn.close(); return stock; }
// FIX: try-with-resources closes on every path static int stockOf(String sku) throws SQLException { try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement ps = conn.prepareStatement(SQL)) { ps.setString(1, sku); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { throw new IllegalArgumentException("Unknown SKU " + sku); } return rs.getInt("stock"); } } }
interface StockLookup { int stock(String sku) throws SQLException; }
static int leftOpen(Connection watcher, StockLookup lookup) throws SQLException, InterruptedException { int before = threadsConnected(watcher); for (String sku : new String[] {"MOB-RN13", "BK-XXXX", "LAP-IPS3", "FSH-NONE", "HK-NONE", "BK-CLEAN"}) { try { lookup.stock(sku); } catch (IllegalArgumentException e) { } } return threadsConnected(watcher) - before; }
static int threadsConnected(Connection watcher) throws SQLException, InterruptedException { Thread.sleep(300); // a closed connection takes a moment to leave the server's count try (Statement st = watcher.createStatement(); ResultSet rs = st.executeQuery("SHOW GLOBAL STATUS LIKE 'Threads_connected'")) { rs.next(); return rs.getInt("Value"); } }
public static void main(String[] args) throws SQLException, InterruptedException { try (Connection watcher = DriverManager.getConnection(URL, USER, PASSWORD)) { System.out.println("Fixed version left open: " + leftOpen(watcher, ErrorPathLeakDemo::stockOf)); System.out.println("Leaky version left open: " + leftOpen(watcher, ErrorPathLeakDemo::stockOfLeaky)); } }}Fixed version left open: 0 Leaky version left open: 2
What this code does
- Both methods are called with three known and three unknown SKUs. The fixed method leaves nothing open; the leaky one leaks once per unknown SKU, because the
throwjumps over its close calls. - Your leaky number may be 1, 2 or 3: Connector/J's cleanup thread sometimes closes unreachable connections after a garbage collection. Any number above 0 is a leak.
threadsConnectedwaits 300 ms first, because a just-closed connection takes a moment to leave the server's count.
A throw for a missing row, an early return or a failed query jumps over those lines, and the connection leaks. These leaks hide well, because they happen only when something else already failed. The fix is always the same: declare every JDBC object in a try-with-resources header.
Find the bug
Find the leak
Select the line that is wrong.
The connection leaks when the SKU is unknown. Which line?
Round 1 of 2getConnection, prepareStatement, createStatement and executeQuery that are not inside a try ( ... ) header.Mistake 2: a new statement for every row
Com_stmt_prepare is a MySQL status counter of how many times the server was asked to prepare a statement. A prepared statement is meant to be prepared once and run many times.
Creating a PreparedStatement inside a loop makes the server prepare the same SQL on every pass. Example 2 counts the prepares, with the statement inside and outside the loop.
Example 2 · Prepare once, run many times
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;import java.util.List;import java.util.Properties;
public class PrepareOnceDemo { static final String SQL = "SELECT name FROM products WHERE sku = ?"; static final List<String> SKUS = List.of("MOB-RN13", "MOB-GM35", "MOB-IP15", "LAP-IPS3", "LAP-HPV15", "ACC-AD141", "ACC-PB20K", "ACC-M331", "BK-CLEAN", "BK-PRAG");
// Works and closes everything, but asks the server to prepare the same SQL ten times static void prepareInsideLoop(Connection conn) throws SQLException { for (String sku : SKUS) { try (PreparedStatement ps = conn.prepareStatement(SQL)) { ps.setString(1, sku); try (ResultSet rs = ps.executeQuery()) { rs.next(); } } } }
// Better: one statement, prepared once, reused for every row, closed once static void prepareOnce(Connection conn) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(SQL)) { for (String sku : SKUS) { ps.setString(1, sku); try (ResultSet rs = ps.executeQuery()) { rs.next(); } } } }
static int prepares(Connection conn) throws SQLException { try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SHOW SESSION STATUS LIKE 'Com_stmt_prepare'")) { rs.next(); return rs.getInt("Value"); } }
public static void main(String[] args) throws SQLException { Properties props = new Properties(); props.setProperty("user", System.getenv("DB_USER")); props.setProperty("password", System.getenv("DB_PASSWORD")); props.setProperty("useServerPrepStmts", "true");
try (Connection conn = DriverManager.getConnection(System.getenv("DB_URL"), props)) { int start = prepares(conn); prepareInsideLoop(conn); int afterLoop = prepares(conn); prepareOnce(conn); int afterOnce = prepares(conn); System.out.println("Prepared inside the loop: " + (afterLoop - start) + " prepares for 10 lookups"); System.out.println("Prepared once: " + (afterOnce - afterLoop) + " prepare for 10 lookups"); } }}Prepared inside the loop: 10 prepares for 10 lookups Prepared once: 1 prepare for 10 lookups
What this code does
Com_stmt_preparecounts how many statements this session asked the server to prepare. WithuseServerPrepStmts=true, the loop version prepares the same SQL 10 times; the fixed version once.- Both versions are leak-free thanks to try-with-resources. The second one also saves a round trip to the server per row.
- In the second version the statement's try is outside the loop and only the result set's try is inside it.
Open the statement once, before the loop, in a try-with-resources header. Inside the loop, set the parameters, run the query and close each ResultSet in its own small try. A forgotten close inside the loop would also leak every statement it creates.
Mistake 3: deciding by the message text
lc_messages is the MySQL setting for the language of error messages. A server set to German sends Doppelter Eintrag ... instead of Duplicate entry ....
Code such as e.getMessage().contains("Duplicate") looks harmless, yet it breaks. Example 3 compares it with getErrorCode() on two different errors.
Example 3 · Mistake: matching on the message text
import java.sql.SQLException;import java.util.List;
public class MessageMatchingDemo { // BUG: decides by the words in the message static boolean isDuplicateEmailByText(SQLException e) { return e.getMessage().contains("Duplicate"); }
// FIX: decides by MySQL's error code static boolean isDuplicateKey(SQLException e) { return e.getErrorCode() == 1062; }
public static void main(String[] args) { // Real MySQL messages: duplicate email, schema bug, then a German duplicate email List<SQLException> errors = List.of( new SQLException("Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'", "23000", 1062), new SQLException("Duplicate column name 'email'", "42S21", 1060), new SQLException("Doppelter Eintrag 'asha.rao@example.com' für Schlüssel 'customers.uq_customers_email'", "23000", 1062));
for (SQLException e : errors) { System.out.println(e.getErrorCode() + " " + e.getSQLState() + " | by text: " + isDuplicateEmailByText(e) + " | by code: " + isDuplicateKey(e)); } }}1062 23000 | by text: true | by code: true 1060 42S21 | by text: true | by code: false 1062 23000 | by text: false | by code: true
What this code does
- The three messages are real MySQL messages; the third came from a server with
SET lc_messages = 'de_DE'. - Matching on text gets two of three wrong: it calls a schema bug (1060) a duplicate email, and misses the German duplicate. Matching on the code gets all three right.
- The state
23000is the same for the first and third errors, which is why the state class alone cannot tell a duplicate from a foreign key problem.
Other errors contain the same word, such as Duplicate column name (1060), which is a schema bug and not a user mistake. Decide with getErrorCode() for exact MySQL cases and with the SQL state class for groups. Keep getMessage() for logs.
Predict the output
Does the message test work?
Read the code and pick what it prints.
Round 1 of 2
The server language is German, and a duplicate email is inserted (error 1062).
Mistake 4: losing the cause, or swallowing the error
throw new DataAccessException("Could not load orders: " + e.getMessage()) keeps only the text. Example 4 prints the chain with the cause lost, then with it kept.
Example 4 · Mistake: copying the message instead of keeping the cause
import java.net.ConnectException;import java.sql.SQLException;
class DataAccessException extends RuntimeException { DataAccessException(String message) { super(message); }
DataAccessException(String message, Throwable cause) { super(message, cause); }}
public class LostCauseDemo { static SQLException connectionFailure() { return new SQLException("Communications link failure", "08S01", new ConnectException("Connection refused")); }
static void printChain(String title, Throwable top) { System.out.println(title); for (Throwable t = top; t != null; t = t.getCause()) { System.out.println(" " + t.getClass().getSimpleName() + ": " + t.getMessage()); } }
public static void main(String[] args) { SQLException e = connectionFailure();
// BUG: only the text survives; the state, the stack trace and the root cause are gone printChain("Message copied:", new DataAccessException("Could not load orders: " + e.getMessage()));
// FIX: the original exception is passed on as the cause printChain("Cause kept:", new DataAccessException("Could not load orders", e)); }}Message copied: DataAccessException: Could not load orders: Communications link failure Cause kept: DataAccessException: Could not load orders SQLException: Communications link failure ConnectException: Connection refused
What this code does
- Copying
e.getMessage()leaves a chain of one: the log would never show the SQL state or that the connection was refused. - Passing
eas the cause keeps the whole chain down toConnectException, so the developer sees the root cause straight away.
The SQL state, the error code, the stack trace and the root cause, such as ConnectException: Connection refused, are gone from the log. Always pass the original as the cause: new DataAccessException("Could not load orders", e). And never end a catch with nothing, a print or a fake return value: catch, translate, rethrow, and let the top layer show a message and log once.
Next step
Check your understanding
12 quick questions