Sobes.tech
Junior — Middle

Could you explain what a cursor is in the context of working with databases?

sobes.tech AI

Answer from AI

A cursor in the context of working with databases is an object that allows sequential traversal of query results obtained from the database. It acts as a pointer to the current row in the dataset returned by an SQL query.

With a cursor, you can:

  • Navigate through the results (for example, row by row)
  • Retrieve data from one or multiple rows
  • Perform update or delete operations on the current row

In Java, cursors are usually implemented through the ResultSet interface, which provides methods for navigation and reading data.

An example of using a cursor in Java:

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

while (rs.next()) {
    String name = rs.getString("name");
    int age = rs.getInt("age");
    System.out.println(name + " - " + age);
}
rs.close();
stmt.close();

Thus, a cursor helps efficiently work with large datasets without loading them entirely into memory.