What is ResultSet in Java: Explanation and Example
ResultSet in Java is an object that holds data retrieved from a database after executing a query. It acts like a table of data you can move through row by row to read the results.How It Works
Imagine you ask a librarian for a list of books matching your search. The librarian gives you a printed list you can read one line at a time. In Java, when you ask a database for data using a query, the ResultSet is like that printed list. It holds all the rows of data returned by the database.
You can move through this list one row at a time using methods like next(). For each row, you can get the values of columns by their names or positions. This way, you can process or display the data as needed.
Example
ResultSet to read and print the data.import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ResultSetExample { public static void main(String[] args) { String url = "jdbc:sqlite::memory:"; // Using in-memory SQLite database try (Connection conn = DriverManager.getConnection(url); Statement stmt = conn.createStatement()) { // Create a sample table stmt.execute("CREATE TABLE users (id INTEGER, name TEXT)"); // Insert sample data stmt.execute("INSERT INTO users (id, name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')"); // Query the table ResultSet rs = stmt.executeQuery("SELECT id, name FROM users"); // Loop through the ResultSet while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("User ID: " + id + ", Name: " + name); } } catch (Exception e) { e.printStackTrace(); } } }
When to Use
Use ResultSet whenever you need to read data from a database after running a query. It is essential for applications that work with databases, such as websites, desktop apps, or mobile apps that show stored information.
For example, if you want to display a list of users, products, or orders stored in a database, you run a query and use ResultSet to get and process that data row by row.
Key Points
- ResultSet holds data returned by a database query.
- You move through rows using
next(). - Access column data by name or index.
- Always close
ResultSetand related resources to avoid leaks. - Works with
StatementorPreparedStatementobjects.