import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSetExample { public static void main(String[] args) { try { // Establish connection to database Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // Create a statement Statement stmt = conn.createStatement(); // Execute query and retrieve result set ResultSet rs = stmt.executeQuery("SELECT * FROM customers"); // Iterate over result set and print data while (rs.next()) { System.out.println("Customer ID: " + rs.getInt("id")); System.out.println("Name: " + rs.getString("name")); System.out.println("Email: " + rs.getString("email")); System.out.println("Address: " + rs.getString("address")); System.out.println("------------------------"); } // Close resources rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { System.err.println("Error: " + e.getMessage()); } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSetExample { public static void main(String[] args) { try { // Establish connection to database Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // Create a statement Statement stmt = conn.createStatement(); // Execute query and retrieve result set ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS total FROM orders"); // Get total count from result set int totalCount = rs.getInt("total"); // Print total count System.out.println("Total orders: " + totalCount); // Close resources rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { System.err.println("Error: " + e.getMessage()); } } }In this example, we establish a connection to a MySQL database, create a statement, execute a query to retrieve the total number of orders from a table called "orders", get the total count from the result set using the alias "total", and print the count to the console. The java.util.ResultSet class is part of the Java Database Connectivity (JDBC) API, which is included in the Java Standard Edition (SE) Library.