File Handling & JDBC · Lesson 115 of 150
ResultSet
ResultSet represents the table of data returned after running a SQL query, like a SELECT statement. It lets you move through the returned rows and read column values one at a time.
01What is ResultSet?
ResultSet represents the table of data returned after running a SQL query, like a SELECT statement. It lets you move through the returned rows and read column values one at a time.
02Why is it used?
After running a query, you need a way to actually access and use the returned data. ResultSet provides this row-by-row access to the results, along with methods to read specific columns by name or position.
03Real-Life Example
Think of receiving a printed report after submitting a request, with each row representing one record, and columns holding specific details. ResultSet is how a Java program reads through this "report" one row at a time.
04Syntax
javaResultSet rs = statement.executeQuery("SELECT * FROM table"); while (rs.next()) { String value = rs.getString("columnName"); }
05Example Program
javaimport java.sql.*; public class ResultSetDemo { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/schooldb", "root", "password" ); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name, age FROM students"); while (rs.next()) { System.out.println(rs.getString("name") + " - " + rs.getInt("age")); } conn.close(); } }
Output:
Aditi - 21
Rohan - 22(Actual output depends on the real data present in the students table.)
06Key Points to Remember
rs.next()moves the cursor to the next row and returnsfalseonce there are no more rows.- Column values can be retrieved using column names (
getString("name")) or column index positions. - The cursor initially starts before the first row, so
next()must be called at least once before reading any data.