A Java object asks a database a question
The course objective names JDBC even though the unit list does not. This short bridge shows the complete path: open a connection, send a parameterized query, read rows, and close every resource safely.
After this lesson
You should be able to
- Name the Connection, PreparedStatement, and ResultSet roles in one query.
- Use try-with-resources so database resources close on success or failure.
Three objects, three jobs
A Connection represents one live conversation with a database. A PreparedStatement represents one SQL command with placeholders for values. A ResultSet is the cursor over rows returned by a SELECT. Keeping those jobs separate makes the code readable and lets the JDBC driver manage database-specific details behind standard Java interfaces.
PreparedStatement is also the safe way to supply values. The SQL structure stays fixed while setInt or setString supplies data separately, so a student's input cannot become part of the SQL grammar. Do not build queries by joining raw input into a String.
String sql = "SELECT name FROM student WHERE roll_no = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, rollNumber);
try (ResultSet rows = statement.executeQuery()) {
while (rows.next()) {
System.out.println(rows.getString("name"));
}
}
}Make the idea stick
Now try it yourself
Run one safe database query
Order the JDBC resource flow from connection to cleanup.
The compiler cannot provide a database
The external Java compiler can check JDBC syntax only if the required driver and database are available, which a simple online compiler normally does not provide. For this pilot, reason about the resource flow here; a later database lab can supply an isolated database and test data. The course must never embed real database passwords in a lesson or browser bundle.
Try it yourself
Modify the query to fetch name and marks for one department supplied as text.
Need a hint?
Use WHERE department = ? and setString(1, department). Keep the value out of the SQL String.
Check the worked solution
The placeholder preserves a fixed query structure while setString supplies the department as data.
String sql = "SELECT name, marks FROM student WHERE department = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, department);
try (ResultSet rows = statement.executeQuery()) {
while (rows.next()) {
System.out.println(rows.getString("name") + " " + rows.getInt("marks"));
}
}
}Quick check
Why is PreparedStatement preferred when a query contains student-supplied text?
Why this lesson exists
Syllabus mapping
Course Objective 4: To Develop data-centric applications using JDBC. · Outcome bridge — JDBC is named in the official objective but omitted from the unit topic list.
Maps to course outcome CO1.