Slip No 27 Q B

Write a Java Program for the implementation of scrollable ResultSet. Assume Teacher table with attributes (TID, TName, Salary, Subject) is already created.

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

public class ScrollableResultSetDemo {
    public static void main(String[] args) {
        try {
            // Load JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Create connection
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/your_database",
                    "username",
                    "password"
            );

            // Create Statement with scrollable ResultSet
            Statement stmt = con.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY
            );

            // Execute query
            ResultSet rs = stmt.executeQuery(
                    "SELECT * FROM Teacher"
            );

            System.out.println("---- Forward Direction ----");
            while (rs.next()) {
                System.out.println(
                        rs.getInt("TID") + " " +
                        rs.getString("TName") + " " +
                        rs.getDouble("Salary") + " " +
                        rs.getString("Subject")
                );
            }

            System.out.println("\n---- Backward Direction ----");
            while (rs.previous()) {
                System.out.println(
                        rs.getInt("TID") + " " +
                        rs.getString("TName") + " " +
                        rs.getDouble("Salary") + " " +
                        rs.getString("Subject")
                );
            }

            System.out.println("\n---- First Record ----");
            if (rs.first()) {
                System.out.println(
                        rs.getInt("TID") + " " +
                        rs.getString("TName") + " " +
                        rs.getDouble("Salary") + " " +
                        rs.getString("Subject")
                );
            }

            System.out.println("\n---- Last Record ----");
            if (rs.last()) {
                System.out.println(
                        rs.getInt("TID") + " " +
                        rs.getString("TName") + " " +
                        rs.getDouble("Salary") + " " +
                        rs.getString("Subject")
                );
            }

            // Close resources
            rs.close();
            stmt.close();
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top