Advanced level · Module 3: Databases with JDBC · Lesson 2 of 4
Connecting with JDBC
Open database connections from Java, run queries with PreparedStatement and map results to objects.
In this lesson you will
- Open a connection and run queries with PreparedStatement
- Map ResultSet rows to records and close resources with try-with-resources
Key concepts
JDBC URL and driverConnectionPreparedStatementResultSet
The lesson
JDBC is Java's standard API for relational databases. Add the database's JDBC driver as a Maven dependency, then open a connection with DriverManager.getConnection(url, user, password). Keep the URL and credentials in configuration, not in the source code.
A PreparedStatement holds SQL with ? placeholders: SELECT * FROM patient WHERE phone = ?. Set values with setString(1, phone) and run with executeQuery() for reads or executeUpdate() for changes.
A ResultSet is read row by row with next(). Map each row to an object, for example new Patient(rs.getLong("id"), rs.getString("name")). Connections, statements and result sets must all be closed; declare them in try-with-resources.
Step by step
- Add the database driver dependency to pom.xml.
- Open a connection and run a simple SELECT.
- Use a PreparedStatement with a parameter.
- Map rows to Patient records in a list.
Saving a patient safely with JDBC
The sequence for one database write: configuration, connection, parameterised SQL, transaction and clean-up.
Read configuration
Load the JDBC URL, user and password from environment variables or a properties file — never hard-code them.
Open a connection
try (Connection c = DriverManager.getConnection(url, user, pass)) so the connection is always closed.
Start a transaction
c.setAutoCommit(false) when the operation changes more than one table or row.
Prepare the SQL
INSERT INTO patient (name, phone) VALUES (?, ?) — placeholders, never string concatenation.
Bind and execute
ps.setString(1, name); ps.setString(2, phone); ps.executeUpdate(); — user input is treated as data only.
Commit or roll back
c.commit() when every statement succeeded; c.rollback() in the catch block so no half-saved data remains.
Result
The patient is saved completely or not at all, the query cannot be hijacked by SQL injection and no connection is left open.
Practice activity
Write a PatientRepository with findAll, findByPhone and save methods using JDBC.
Expected result: The methods pass integration tests against a test database, and all resources are closed.
Check your understanding
-
Which JDBC method runs a SELECT?
Show answer
executeQuery().
-
Where should database passwords be kept?
Show answer
In configuration or environment variables, never in source code.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.