Building Database Applications with JDBC
Building Database Applications with JDBC tests connections, statements, result sets, transactions, and resource cleanup.
Core rules
DriverManager.getConnection(url, user, password)returns aConnection. JDBC 4 auto-loads drivers from the classpath.Statementexecutes static SQL;PreparedStatementis precompiled, uses?placeholders, prevents SQL injection, and is generally preferred. Parameter indexes start at 1.executeQuery()returns aResultSetforSELECT;executeUpdate()returns an affected-row count for DML and 0 for DDL.execute()returns a boolean.- The
ResultSetcursor starts before the first row; callnext()before reading. Column labels are case-insensitive by default. - Use
getInt,getString,getObject, etc.;wasNull()checks whether the last read SQLNULLwas returned as a Java primitive. - Transactions: set
autoCommit(false), perform work, thencommit()orrollback().Savepointallows partial rollback. - Try-with-resources closes
ResultSet,Statement, andConnectionin reverse order.
Worked example
try (Connection c = DriverManager.getConnection(url); PreparedStatement ps = c.prepareStatement("UPDATE emp SET name=? WHERE id=?")) { ps.setString(1, "Ada"); ps.setInt(2, 7); int rows = ps.executeUpdate(); }
The first placeholder is index 1, the second index 2. executeUpdate() returns the number of rows changed.
Traps
- Using index 0 for a
PreparedStatementparameter throwsSQLException. - Reading a
ResultSetbefore callingnext()is invalid. getInt()on SQLNULLreturns 0; usewasNull()to distinguish it from a real 0.- Leaving
autoCommittrue means each statement commits immediately. - Concatenating user input into SQL invites injection; use parameters.
SQLExceptionis checked and may carry aSQLStateand vendor error code.