Java - JDBC - ResultSet Interface

The ResultSet interface in Java provides methods for retrieving data from a database after executing a SQL query. It represents a set of rows containing the query results.

Here are some of the important methods in the ResultSet interface:

  • next(): moves the cursor to the next row in the result set
  • getInt(int columnIndex) / getInt(String columnName): retrieves the value of the specified column as an int
  • getDouble(int columnIndex) / getDouble(String columnName): retrieves the value of the specified column as a double
  • getString(int columnIndex) / getString(String columnName): retrieves the value of the specified column as a String
  • getDate(int columnIndex) / getDate(String columnName): retrieves the value of the specified column as a java.sql.Date

Here's an example of how to use the ResultSet interface:

try {
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
    
    while (rs.next()) {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        double price = rs.getDouble("price");
        Date date = rs.getDate("date");
        
        System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price + ", Date: " + date);
    }
    
    rs.close();
    stmt.close();
    conn.close();

} catch (SQLException e) {
    System.out.println("SQL error: " + e.getMessage());
}

This code retrieves all rows from the mytable table in the mydatabase database, and prints out the id, name, price, and date columns for each row. Note that the close() method is called on the ResultSet, Statement, and Connection objects to release the resources when finished.