How do you use ResultSet with a simple code example?

ResultSet in Java is used to retrieve data from a database after executing a query. It contains methods for navigating and extracting data from the retrieved records.

Here is a simple example demonstrating how to use the ResultSet in Java:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Example { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // Establish a connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password"); // Create a statement stmt = conn.createStatement(); // Execute a query rs = stmt.executeQuery("SELECT * FROM users"); // Process the ResultSet while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }

ResultSet Java JDBC Database SQL