JDBC essentials
On this page 8 topics
Overview
Topics
- Driver dependency
- DriverManager
- Connection
- PreparedStatement
- ResultSet
- try-with-resources
- SQL injection
Learn first
70 min of reading · 3 h of practice (estimate)
Learning outcomes
- Add the PostgreSQL JDBC driver with Maven and open a connection from configuration (not hard-coded credentials).
- Execute queries and updates with
PreparedStatementand mapResultSetrows to objects. - Close connections, statements, and result sets with try-with-resources.
- Demonstrate a SQL injection with string concatenation and prevent it with parameters.
- Group related statements in a transaction with
setAutoCommit(false),commit, androllback.
Lessons
- 01How Java talks to a database10 min read
- 02Connecting: driver, URL, credentials from environment variables10 min read
- 03Querying and mapping rows to objects10 min read
- 04SQL injection, live10 min read
- 05Transactions from Java9 min read
- 06Demo: building the BookRepository with JDBC10 min read
- 07Demo: SQL injection, then the PreparedStatement fix11 min read
Lab and exercises
Lab
BEG-055-LAB1 · Library DAO
Outcomes: 1–5 · Time: ~3 h Write a BookRepository interface with a JDBC implementation (save, findById returning Optional, findByTitle, delete) and integration tests against a local test database. Acceptance: no string-concatenated SQL; resources closed; tests pass.
Exercises (assessment: implement a new repository method with a test; explain why parameters prevent injection)
| ID | Outcome | Task |
|---|---|---|
| BEG-055-EX01 | 1 | Add the PostgreSQL driver with Maven and connect using DB_URL, DB_USER, DB_PASSWORD environment variables. |
| BEG-055-EX02 | 2 | Write findAll() returning a List<Book> mapped from a ResultSet. |
| BEG-055-EX03 | 2 | Write findById(int) returning Optional<Book>. |
| BEG-055-EX04 | 3 | Rewrite a method that closes resources manually using try-with-resources. |
| BEG-055-EX05 | 4 | Demonstrate injection against a concatenated query, then fix it with parameters. |
| BEG-055-EX06 | 5 | Write a method that inserts a loan and reduces copies in one transaction with rollback on error. |
| BEG-055-EX07 | 1 | Check that no password appears in the code or the Git history of your project. |
| BEG-055-EX08 | 2 | Implement a new method findByTitleContaining(String) using LIKE ? and write an integration test for it. (A lookup by author needs a join through book_authors; try it only as a stretch task.) |
Show solutions
- EX01 Dependency
org.postgresql:postgresql(verify version);DriverManager.getConnection(System.getenv("DB_URL"), ...). - EX02 Loop
while (rs.next()), addnew Book(rs.getInt("id"), rs.getString("title"))to a list. - EX03
if (rs.next()) return Optional.of(map(rs)); return Optional.empty(); - EX04
try (Connection c = ...; PreparedStatement ps = c.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { ... } - EX05 Input
x' OR '1'='1returns all rows with concatenation; with?it returns none because the value is data. - EX06
setAutoCommit(false); twoexecuteUpdatecalls;commit();catchcallsrollback()and rethrows. - EX07 Credentials come from environment variables;
git log -pand a search for the password show no match. - EX08
SELECT ... WHERE title LIKE ?with the parameter"%" + text + "%"(bound throughsetString, never concatenated); the test inserts two books, queries, and asserts the result. Stretch: joinbooks,book_authors, andauthorsto filter by author name.
Quiz
Outcomes: O1 driver and connection · O2 queries and mapping · O3 try-with-resources · O4 SQL injection · O5 transactions.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Implement a new repository method with an integration test and explain why parameters prevent injection (EX08 and the lab). Pass: at least 8 of 10 quiz questions, no concatenated SQL, resources closed, tests pass.
Common mistakes
Concatenating user input into SQL; leaking connections; credentials committed to Git.
Assessment
Implement a new repository method with a test; explain why parameters prevent injection.
Career relevance
JNR-025 to JNR-029 build on this toward Spring Data JPA.