Sobes.tech
Junior — Middle

Can you explain what ResultSet is and how to use it when working with a database?

sobes.tech AI

Answer from AI

ResultSet is an interface in Java that represents a table of data obtained as a result of executing an SQL query on a database.

Key points of using ResultSet:

  • It contains rows and columns of data retrieved from the database.
  • Access to data is done through a cursor, which initially is positioned before the first row.
  • To move to the next row, the next() method is called, which returns true if there is a row.
  • Data from the current row can be obtained using methods like getInt(), getString(), getDouble(), etc., specifying the column name or index.

Example of usage:

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name FROM users");

while (rs.next()) {
    int id = rs.getInt("id");
    String name = rs.getString("name");
    System.out.println("User: " + id + ", Name: " + name);
}
rs.close();
stmt.close();

It is important to close the ResultSet and related resources after use to prevent memory leaks.

Thus, ResultSet is used for iterating over and reading data retrieved from the database in a Java application.

Can you explain what ResultSet is and how to use it… - sobes.tech