import java.sql.*; public class Example1 { public static void main(String[] args) { try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root","password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * from customers"); while (rs.next()) { System.out.println(rs.getString("name")); System.out.println(rs.getInt("age")); } conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
import java.sql.*; public class Example2 { public static void main(String[] args) { try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root","password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * from orders"); for (int i=1; i<=5; i++) { if (rs.next()) { System.out.println(rs.getString("order_id")); System.out.println(rs.getDouble("total_amount")); } } conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }In this example, we have retrieved all the rows from the orders table and printed the values of the order_id and total_amount columns for the first five rows only. We have used the next() method in a for loop to move the cursor to the next row in each iteration. The java.util.ResultSet is part of the Java Database Connectivity (JDBC) API, which is included in the java.sql package.