Concept Explanation
Almost every database interaction is one of four operations, remembered as CRUD:
| Letter | Operation | SQL | JDBC method |
|---|---|---|---|
| C | Create | INSERT | executeUpdate() |
| R | Read | SELECT | executeQuery() |
| U | Update | UPDATE | executeUpdate() |
| D | Delete | DELETE | executeUpdate() |
The key distinction: executeQuery() returns a ResultSet of rows; executeUpdate() returns an int count of affected rows.
Create
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement pst =
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
pst.setString(1, "Ada");
pst.setString(2, "ada@example.com");
pst.executeUpdate();
try (ResultSet keys = pst.getGeneratedKeys()) {
if (keys.next()) {
System.out.println("New id: " + keys.getLong(1));
}
}
}
Read
String sql = "SELECT id, name, email FROM users WHERE active = ?";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setBoolean(1, true);
try (ResultSet rs = pst.executeQuery()) {
while (rs.next()) { // advances one row at a time
long id = rs.getLong("id");
String name = rs.getString("name");
System.out.println(id + ": " + name);
}
}
}
Update and Delete
try (PreparedStatement pst =
conn.prepareStatement("UPDATE users SET email = ? WHERE id = ?")) {
pst.setString(1, "new@example.com");
pst.setLong(2, 42L);
int changed = pst.executeUpdate();
System.out.println(changed + " row(s) updated");
}
try (PreparedStatement pst =
conn.prepareStatement("DELETE FROM users WHERE id = ?")) {
pst.setLong(1, 42L);
if (pst.executeUpdate() == 0) {
System.out.println("Nothing matched — id may not exist");
}
}
Common Mistakes
- Forgetting
rs.next(): A fresh ResultSet sits before the first row. Reading without callingnext()throws. executeQueryfor an INSERT: Wrong method — you will get an exception. UseexecuteUpdate.- UPDATE or DELETE without WHERE: You will modify every row in the table. There is no undo.
- Ignoring the return count: A count of 0 means nothing matched, which is often a real bug worth reporting.
Best Practices
- Always check the affected-row count before reporting success to the user.
- Select named columns, not
SELECT *— your code then survives schema changes. - Read by column name (
rs.getString("name")), not index; reordering the SELECT will not break you.
Practice Exercises
- The Full Cycle: Write four methods —
create,findById,update,delete— against aproductstable, and call all four in sequence frommain. - The Generated Key: Insert a row and print the auto-generated primary key using
getGeneratedKeys(). - The Safe Delete: Write a delete that reports "not found" instead of silently succeeding when no row matches.