ScrollableRs.java Source code

Java tutorial

Introduction

Here is the source code for ScrollableRs.java

Source

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ScrollableRs {
    public static void main(String[] args) throws Exception {
        Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
        String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
        Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = stmt.executeQuery("SELECT ssn, name, salary FROM EMPLOYEES");
        while (rs.next()) {
            printRow(rs);
        }
        rs.afterLast();
        System.out.println("\"After-last-row\" = " + rs.isAfterLast());
        rs.beforeFirst();
        System.out.println("\"Before-first-row\" = " + rs.isBeforeFirst());
        rs.first();
        printRow(rs);
        rs.last();
        printRow(rs);
        rs.previous();
        printRow(rs);

        rs.next();
        printRow(rs);

        rs.absolute(3);
        printRow(rs);

        rs.relative(-2);
        printRow(rs);
        if (conn != null)
            conn.close();
    }

    public static void printRow(ResultSet rs) throws SQLException {
        int ssn = rs.getInt("ssn");
        String name = rs.getString("name");
        double salary = rs.getDouble("salary");

        System.out.print("Row Number=" + rs.getRow());
        System.out.print(", SSN: " + ssn);
        System.out.print(", Name: " + name);
        System.out.println(", Salary: $" + salary);
    }
}