Data in a ResultSet
Now that CityBook Libraries can execute queries, you need to extract the actual data from the ResultSet. A ResultSet works like a cursor that moves row by row, and you retrieve column values using getter methods.
Extract the title and publication_year from each book in the results. All necessary imports are available for you.
This exercise is part of the course
Querying a PostgreSQL Database in Java
Exercise instructions
- Move through each row in the
ResultSet. - Retrieve the
titleandpublication_yearcolumns using the appropriate getter methods.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class Main {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection(Credentials.URL, Credentials.USER, Credentials.PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books")) {
// Iterate through each row
while (rs.____()) {
// Retrieve column values
System.out.println(rs.____("title"));
System.out.println(rs.____("publication_year"));
}
}
}
}