CachedRowSet is a disconnected RowSet implementation. It retrieves data from the database, stores the data in memory, and can then be used after the database connection has been closed.
Key Features
- Does not require a continuous database connection.
- Stores rows in memory.
- Can be serialized and transferred between applications.
- Supports scrolling and updating.
- Can reconnect later to synchronize changes with the database.
Program Using CachedRowSet
CachedRowSet is a disconnected RowSet implementation. It retrieves the data from the database and stores it in memory. After the data is fetched, the database connection can be closed while the RowSet continues to be used.
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CachedRowSetExample {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/jdbc_demo";
String username = "root";
String password = "password";
try {
// Create CachedRowSet
CachedRowSet rowSet =
RowSetProvider.newFactory()
.createCachedRowSet();
// Set database properties
rowSet.setUrl(url);
rowSet.setUsername(username);
rowSet.setPassword(password);
rowSet.setCommand(
"SELECT employee_id, employee_name, " +
"department, salary FROM employee");
// Fill CachedRowSet
rowSet.execute();
System.out.println(
"Data Retrieved from Database");
// Close database connection
// CachedRowSet keeps the data in memory
System.out.println(
"\nEmployee Details");
System.out.println(
"-----------------------------");
while (rowSet.next()) {
System.out.println(
rowSet.getInt("employee_id") + " " +
rowSet.getString("employee_name") + " " +
rowSet.getString("department") + " " +
rowSet.getDouble("salary"));
}
rowSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\mysql-connector.jar" CachedRowSetExample.java
PS D:\test> java -classpath ".;D:\test\mysql-connector.jar" CachedRowSetExample
Data Retrieved from Database
Employee Details
-----------------------------
101 Ravi Development 78500.0
102 Priya Operations 71500.0
106 Chakrapani Finance 204000.0
107 Suresh IT 46500.0
108 Anita HR 48500.0
109 Kiran Finance 52000.0
110 Sai IT 45000.0
111 Akhila HR 47000.0
112 Raghu Finance 52000.0
119 Deepak Support 36000.0Code language: CSS (css)
