Part 11 / Topic 10 of 10
Putting it together: an orders database with validated input
Real-world example: the part's second build — JDBC (sections 7–8) plus regex (section 5) plus exception design (section 1), the same shape the Stage 2 project (next) will need for a real Library/Member database. OrdersDatabaseDemo validates a phone number with regex before it ever becomes a database round trip, every query is a PreparedStatement, and every SQLException is wrapped in one unchecked OrderStoreException so the class's public methods never leak a raw java.sql.SQLException to their callers.
int placeOrder(String customer, String phone, String city, double amount) {
if (!PHONE_PATTERN.matcher(phone).matches()) {
throw new IllegalArgumentException("phone must be a 10-digit Indian mobile number, got: " + phone);
}
String sql = "INSERT INTO orders (customer, phone, city, amount) VALUES (?, ?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, customer);
statement.setString(2, phone);
statement.setString(3, city);
statement.setDouble(4, amount);
statement.executeUpdate();
try (ResultSet keys = statement.getGeneratedKeys()) {
keys.next();
return keys.getInt(1);
}
} catch (SQLException e) {
throw new OrderStoreException("could not place order for " + customer, e);
}
}
$ javac -cp lib/sqlite-jdbc-3.50.3.0.jar OrdersDatabaseDemo.java
$ java -cp .:lib/sqlite-jdbc-3.50.3.0.jar OrdersDatabaseDemo
-- placing orders, phone validated by regex first --
placed order #1 (Asha)
placed order #2 (Ravi)
placed order #3 (Meera)
rejected before any query ran: phone must be a 10-digit Indian mobile number, got: 12345
-- orders in Pune, highest amount first --
#2 Ravi Shah 9123456780 Rs 2550.00
#1 Asha Kulkarni 9876543210 Rs 1200.00
total for Pune: Rs 3750.00
total for Chennai: Rs 999.00
total for Nagpur (no orders): Rs 0.00
Two details worth noticing in that last block: SUM(amount) for a city with zero matching orders (Nagpur) returns SQL NULL, and ResultSet.getDouble on a NULL column quietly returns 0.0 rather than throwing — worth knowing before you assume "0.0 total" and "no orders" are always the same thing in your own queries. And the bad phone number (12345) is rejected by IllegalArgumentException before placeOrder builds any SQL at all — regex is nearly free to run, a round trip to the database is not, so validate the cheap way first.
Full program: examples/OrdersDatabaseDemo.java.
Done here? The practice set for Part 11 — including the solutions — is on the part page.