What is mean by cached row set? Explain with suitable example.

  •  A CachedRowSet object is a container for rows of data that caches its rows in memory, which makes it possible to operate without always being connected to its data source. 
  • A CachedRowSet object typically contains rows from a result set, but it can also contain rows from any file with a tabular format, such as a spreadsheet. The reference implementation supports getting data only from a ResultSet object, but developers can extend the SyncProvider implementations to provide access to other tabular data sources.
  • An application can modify the data in a CachedRowSet object, and those modifications can then be propagated back to the source of the data.
  • A CachedRowSet object is a disconnected rowset, which means that it makes use of a connection itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being to its data source only briefly. It connects to its data source while it is reading data to populate modified.
  • A CachedRowSet is a RowSet in which the rows are cached and the RowSet is disconnected, that is, it does not maintain an active connection to the database. 
  • The oracle.jdbc.rowset.OracleCachedRowSet class is the Oracle implementation of CachedRowSet. It can interoperate with the reference implementation of Sun Microsystems. The OracleCachedRowSet class in the ojdbc14.jar file implements the standard JSR-114 interface javax.sql.rowset.CachedRowSet.

                                    OR,

CachedRowSet

A CachedRowSet object is a container for rows of data that caches its rows in memory, which makes it possible to operate (scroll and update) without keeping the database connection open all the time.

A CachedRowSet object makes use of a connection to the database only briefly: while it is reading data to populate itself with rows, and again while it is committing changes to the underlying database. So the rest of the time, a CachedRowSet object is disconnected, even while its data is being modified. Hence it is called disconnected row set.

Being disconnected, a CachedRowSet object is much leaner than a ResultSet object, making it easier to pass a CachedRowSet object to another component in an application.

You can modify data in a CachedRowSet object, but the modifications are not immediately reflected in the database. You need to make an explicit request to accept accumulated changes (insert, update and delete rows). The CachedRowSet then reconnects to the database and issues SQL statements to commit the changes.

A Complete CachedRowSet Example Program
Let’s see a complete program that demonstrates how to use CachedRowSet. The following program populates rows from student table in a MySQL database named college. Then it asks the user to update, delete and insert rows interactively.
Here’s the code of the program:
import java.sql.*;
import javax.sql.rowset.*;
import javax.sql.rowset.spi.*;
import java.io.*;
 
/**
 * This program demonstrates how to use CachedRowSet in JDBC.
 *
 * @author www.codejava.net
 */
public class CachedRowSetExample {
    static Console console = System.console();
    static String answer;
    static boolean quit = false;
 
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/college";
        String username = "root";
        String password = "password";
 
        try (Connection conn = DriverManager.getConnection(url, username, password)) {
            conn.setAutoCommit(false);
 
            String sql = "SELECT * FROM student";
 
            Statement statement = conn.createStatement();
 
            ResultSet result = statement.executeQuery(sql);
 
            RowSetFactory factory = RowSetProvider.newFactory();
            CachedRowSet rowset = factory.createCachedRowSet();
 
            rowset.setTableName("student");
 
            rowset.populate(result);
 
            while (!quit) {
                if (!readStudent(rowset)) continue;
 
                updateStudent(rowset);
 
                deleteStudent(rowset);
 
                insertStudent(rowset);
 
                saveChanges(rowset, conn);
 
                askToQuit();
 
            }
 
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
 
    }
 
    static void readStudentInfo(String position, ResultSet result)
            throws SQLException {
        String name = result.getString("name");
        String email = result.getString("email");
        String major = result.getString("major");
 
        String studentInfo = "%s: %s - %s - %s\n";
        System.out.format(studentInfo, position, name, email, major);
    }
 
    static boolean readStudent(ResultSet result) throws SQLException {
        int row = Integer.parseInt(console.readLine("Enter student number: "));
 
        if (result.absolute(row)) {
            readStudentInfo("Student at row " + row + ": ", result);
            return true;
        } else {
            System.out.println("There's no student at row " + row);
            return false;
        }
    }
 
    static void updateStudent(ResultSet result) throws SQLException {
        answer = console.readLine("Do you want to update this student (Y/N)?: ");
 
        if (answer.equalsIgnoreCase("Y")) {
            String name = console.readLine("\tUpdate name: ");
            String email = console.readLine("\tUpdate email: ");
            String major = console.readLine("\tUpdate major: ");
 
            if (!name.equals("")) result.updateString("name", name);
            if (!email.equals("")) result.updateString("email", email);
            if (!major.equals("")) result.updateString("major", major);
 
            result.updateRow();
 
            System.out.println("The student has been updated.");
        }
 
    }
 
    static void deleteStudent(ResultSet result) throws SQLException {
        answer = console.readLine("Do you want to delete this student (Y/N)?: ");
 
        if (answer.equalsIgnoreCase("Y")) {
            result.deleteRow();
 
            System.out.println("The student has been removed.");
        }
 
    }
 
    static void insertStudent(ResultSet result) throws SQLException {
        answer = console.readLine("Do you want to insert a new student (Y/N)?: ");
 
        if (answer.equalsIgnoreCase("Y")) {
            String name = console.readLine("\tEnter name: ");
            String email = console.readLine("\tEnter email: ");
            String major = console.readLine("\tEnter major: ");
 
            result.moveToInsertRow();
 
            result.updateNull("student_id");
            result.updateString("name", name);
            result.updateString("email", email);
            result.updateString("major", major);
 
            result.insertRow();
            result.moveToCurrentRow();
 
            System.out.println("The student has been added.");
        }
 
    }
 
    static void saveChanges(CachedRowSet rowset, Connection conn) {
        answer = console.readLine("Do you want to save changes (Y/N)?: ");
 
        if (answer.equalsIgnoreCase("Y")) {
            try {
                rowset.acceptChanges(conn);
            } catch (SyncProviderException ex) {
                System.out.println("Error commiting changes to the database: " + ex);
            }
        }
    }
 
    static void askToQuit() {
        answer = console.readLine("Do you want to quit (Y/N)?: ");
        quit = answer.equalsIgnoreCase("Y");
    }
}


Comments

Popular posts from this blog

Suppose that a data warehouse for Big-University consists of the following four dimensions: student, course, semester, and instructor, and two measures count and avg_grade. When at the lowest conceptual level (e.g., for a given student, course, semester, and instructor combination), the avg_grade measure stores the actual course grade of the student. At higher conceptual levels, avg_grade stores the average grade for the given combination. a) Draw a snowflake schema diagram for the data warehouse. b) Starting with the base cuboid [student, course, semester, instructor], what specific OLAP operations (e.g., roll-up from semester to year) should one perform in order to list the average grade of CS courses for each BigUniversity student. c) If each dimension has five levels (including all), such as “student < major < status < university < all”, how many cuboids will this cube contain (including the base and apex cuboids)?

Suppose that a data warehouse consists of the three dimensions time, doctor, and patient, and the two measures count and charge, where a charge is the fee that a doctor charges a patient for a visit. a) Draw a schema diagram for the above data warehouse using one of the schemas. [star, snowflake, fact constellation] b) Starting with the base cuboid [day, doctor, patient], what specific OLAP operations should be performed in order to list the total fee collected by each doctor in 2004? c) To obtain the same list, write an SQL query assuming the data are stored in a relational database with the schema fee (day, month, year, doctor, hospital, patient, count, charge)

Suppose that a data warehouse consists of the four dimensions; date, spectator, location, and game, and the two measures, count and charge, where charge is the fee that a spectator pays when watching a game on a given date. Spectators may be students, adults, or seniors, with each category having its own charge rate. a) Draw a star schema diagram for the data b) Starting with the base cuboid [date; spectator; location; game], what specific OLAP operations should perform in order to list the total charge paid by student spectators at GM Place in 2004?