Practice: running queries with JDBC
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 reading bugs come from four habits: the wrong getter, a misplaced next(), a NULL that became 0, and an ignored row count. Can you spot each one and apply its short rule?
Mistake 1: the wrong getter
Read the same GST amounts and an SKU with the wrong getters, and see what each one costs.
Example 1 · Three wrong getters
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.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class WrongGettersDemo { public static void main(String[] args) throws SQLException { String sql = "SELECT sku, price * 0.18 AS gst FROM products WHERE category_id IN (4, 5, 6) " + "ORDER BY product_id"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
double wrongTotal = 0; BigDecimal rightTotal = BigDecimal.ZERO; try (ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { wrongTotal += rs.getDouble("gst"); // wrong: double rightTotal = rightTotal.add(rs.getBigDecimal("gst")); } } System.out.println("GST total, getDouble: " + wrongTotal); System.out.println("GST total, getBigDecimal: " + rightTotal);
try (ResultSet rs = st.executeQuery(sql)) { rs.next(); // wrong: getInt drops the paise System.out.println("getInt(gst) on " + rs.getBigDecimal("gst") + ": " + rs.getInt("gst")); try { System.out.println(rs.getInt("sku")); // wrong: sku is text } catch (SQLException e) { System.out.println("getInt(sku): " + e.getMessage()); } } } }}GST total, getDouble: 1708.5599999999997 GST total, getBigDecimal: 1708.5600 getInt(gst) on 233.8200: 233 getInt(sku): Cannot determine value type from string 'ACC-AD141'
What this code does
- The same GST amounts add up to
1708.5599999999997asdoubleand exactly1708.5600asBigDecimal. getIntturns233.8200into233.getInton the text columnskufails withSQLDataException, because the driver cannot turnACC-AD141into a number.
A wrong getter reads a column into a Java type that cannot hold it exactly. The program compiles and usually runs, so the damage shows up later as a wrong total or a crash on one unusual row. The fix is always the same: look up the column type, then use the getter from the type-mapping table. Review: Column types to Java types (opens in a new tab).
DECIMAL→getBigDecimal, add withadd, round once withsetScale(2, RoundingMode.HALF_UP).COUNT(*),SUMofINT→getLong.VARCHAR,CHAR(includingpincodeandphone) →getString, even when the text looks like a number.
Find the bug
Find the wrong getter
Tap the line that reads a column with the wrong getter.
A product row is read for an invoice.
Round 1 of 2Mistake 2: cursor mistakes
The same query is read three ways: if instead of while, next() twice per row, and one next() in a while.
Example 2 · if instead of while, and next() twice
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;import java.util.ArrayList;import java.util.List;
public class IfInsteadOfWhileDemo { public static void main(String[] args) throws SQLException { String sql = "SELECT name FROM products WHERE category_id = 2 ORDER BY price"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
// Bug: if reads only the first row of a list List<String> withIf = new ArrayList<>(); try (ResultSet rs = st.executeQuery(sql)) { if (rs.next()) { withIf.add(rs.getString("name")); } } System.out.println("with if: " + withIf);
// Bug: next() called twice per loop skips every second row List<String> doubleNext = new ArrayList<>(); try (ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { if (rs.next()) { doubleNext.add(rs.getString("name")); } } } System.out.println("next twice: " + doubleNext);
// Right: while for many rows, one next() per row List<String> withWhile = new ArrayList<>(); try (ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { withWhile.add(rs.getString("name")); } } System.out.println("with while: " + withWhile); } }}with if: [Redmi Note 13 5G] next twice: [Samsung Galaxy M35] with while: [Redmi Note 13 5G, Samsung Galaxy M35, iPhone 15 128GB]
What this code does
- With
if, only the first mobile is read. With a secondnext()inside the loop, the loop skips the Redmi and the iPhone and keeps only the middle row. - Only the version with exactly one
next()per row in awhilereturns all three mobiles.
A cursor mistake moves the ResultSet cursor too little, too much or at the wrong time. Too little: reading before next() gives Before start of result set. At the wrong time: reading after the loop gives After end of result set. The quiet mistakes are worse, because they throw nothing. The rule: exactly one next() per row, while for many rows, if for zero or one. Review: Reading a ResultSet row by row (opens in a new tab).
Predict the output
How many rows are counted?
Pick what is printed.
Round 1 of 2
The query returns 3 rows, and the loop calls next() twice per pass.
Mistake 3: lost NULLs
A LEFT JOIN report reads the same column three ways, to show which one keeps the NULL.
Example 3 · Lost NULLs in a LEFT JOIN report
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;import java.time.LocalDateTime;
public class LostNullDemo { public static void main(String[] args) throws SQLException { String sql = "SELECT p.name, SUM(oi.quantity) AS units_sold, " + "COALESCE(SUM(oi.quantity), 0) AS units_or_zero, MAX(o.ordered_at) AS last_sold " + "FROM products p " + "LEFT JOIN order_items oi ON oi.product_id = p.product_id " + "LEFT JOIN orders o ON o.order_id = oi.order_id " + "WHERE p.category_id IN (4, 7) GROUP BY p.product_id, p.name ORDER BY p.product_id"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { int lost = rs.getInt("units_sold"); // NULL -> 0, no warning Integer kept = rs.getObject("units_sold", Integer.class); // NULL stays null int zero = rs.getInt("units_or_zero"); // SQL already chose 0 LocalDateTime last = rs.getObject("last_sold", LocalDateTime.class); System.out.println(rs.getString("name") + ": getInt=" + lost + ", getObject=" + kept + ", COALESCE=" + zero + ", last sold " + (last == null ? "never" : last.toLocalDate())); } } }}boAt Airdopes 141: getInt=5, getObject=5, COALESCE=5, last sold 2026-09-21 Mi Power Bank 20000mAh: getInt=3, getObject=3, COALESCE=3, last sold 2026-08-30 Logitech M331 Silent Mouse: getInt=1, getObject=1, COALESCE=1, last sold 2026-07-18 Prestige Pressure Cooker 3L: getInt=0, getObject=null, COALESCE=0, last sold never USB-C Cable 1m: getInt=0, getObject=null, COALESCE=0, last sold never
What this code does
- The cooker and the USB-C cable were never ordered, so
SUMandMAXareNULLfor them.getIntshows 0;getObjectshowsnull. COALESCE(SUM(oi.quantity), 0)gives 0 on purpose, in SQL.MAX(o.ordered_at)read as aLocalDateTimelets the report printnever.
A lost NULL is a NULL that a primitive getter turned into 0, false or 0.0. After that, nothing in the program can tell "no value" from a real zero. LEFT JOIN reports are the usual place: a product that was never ordered has NULL for SUM(quantity) and MAX(ordered_at).
First decide what NULL means for the screen. If "never sold" must be shown, read with getObject(col, Integer.class) or getObject(col, LocalDateTime.class) and check for null. If 0 really is the right answer, say so in SQL with COALESCE(SUM(oi.quantity), 0), so the choice is visible in the query instead of hidden in a getter. Review: Column types to Java types (opens in a new tab).
COUNT(...) is never NULL: it returns 0 for no rows. SUM, AVG, MIN and MAX return NULL when there is nothing to add or compare.Mistake 4: ignoring the row count
A courier update runs once without looking at the count and once with it.
Example 4 · A courier update that ignores the count
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.util.List;
public class IgnoredCountDemo { // Bug: the count is thrown away, so every id "works" static void markDeliveredUnchecked(Statement st, int orderId) throws SQLException { st.executeUpdate("UPDATE orders SET status = 'DELIVERED' WHERE status = 'SHIPPED' AND order_id = " + orderId); System.out.println(" order " + orderId + ": delivered"); }
// Fix: the count decides what to report static boolean markDelivered(Statement st, int orderId) throws SQLException { int rows = st.executeUpdate( "UPDATE orders SET status = 'DELIVERED' WHERE status = 'SHIPPED' AND order_id = " + orderId); return rows == 1; }
public static void main(String[] args) throws SQLException { List<Integer> courierList = List.of(14, 15, 404); // 14 is SHIPPED, 15 is only PLACED, 404 does not exist try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
System.out.println("Unchecked:"); for (int id : courierList) { markDeliveredUnchecked(st, id); } st.executeUpdate("UPDATE orders SET status = 'SHIPPED' WHERE order_id = 14");
System.out.println("Checked:"); int done = 0; for (int id : courierList) { if (markDelivered(st, id)) { done++; } else { System.out.println(" order " + id + ": not updated (missing or not SHIPPED)"); } } System.out.println(" delivered " + done + " of " + courierList.size()); st.executeUpdate("UPDATE orders SET status = 'SHIPPED' WHERE order_id = 14"); } }}Unchecked: order 14: delivered order 15: delivered order 404: delivered Checked: order 15: not updated (missing or not SHIPPED) order 404: not updated (missing or not SHIPPED) delivered 1 of 3
What this code does
- The unchecked method prints
deliveredfor all three ids, though order 15 is not shipped yet and order 404 does not exist. - The checked method returns
rows == 1, so the report lists the two failures and saysdelivered 1 of 3. Each run undoes the change to order 14.
Ignoring the row count means calling executeUpdate and throwing away its result. Every id then seems to work: a missing order and an order in the wrong status both update 0 rows without any exception, and the program reports success.
A WHERE that also checks the current state, such as AND status = 'SHIPPED', makes the count more useful: 1 means the change was allowed and done; 0 means the row was missing or not in that state. Return the result to the caller, and when the user needs to know which reason it was, run one small SELECT to find out. Review: executeUpdate for INSERT, UPDATE and DELETE (opens in a new tab).
Order of execution
Mark an order delivered, safely
Tap the steps in the order a careful method does them.
Finish up
Mark complete & continue
Next: Mini project: ShopLite catalog reports