Pagination with JDBC on Derby SQL server without caching all the table
807603Jan 23 2008 — edited Jan 23 2008Ok, Ive searched for this for a long time and couldnt find any examples around. This example is useful for especially derby sql server users, since derby does not support LIMIT or TOP, it is quite hard to enable pagination.
So here's the code
int currentRowIndex = 0;
int maxRowIndex = 0;
int minRowIndex = 0;
boolean directionForward = true;
int maxRowSize = 0;
Connection conn;
Statement stmt;
int currentPaginationIndex = 0;
int totalRowsDisplayed = 0;
private void printToTable() {
try {
ResultSet srs = stmt.executeQuery("SELECT COUNT(0) FROM USER_ROLE");
srs.next();
maxRowSize = srs.getInt(1);
if (directionForward) {
srs = stmt.executeQuery("SELECT * from USER_ROLE where USER_ROLE.ROLE_ID >" + currentRowIndex+" ORDER BY USER_ROLE.ROLE_ID ASC");
} else {
srs = stmt.executeQuery("SELECT * from USER_ROLE where USER_ROLE.ROLE_ID <" + currentRowIndex+" ORDER BY USER_ROLE.ROLE_ID DESC");
}
ResultSetMetaData rsmd = srs.getMetaData();
String[] columnNames = new String[rsmd.getColumnCount()];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = rsmd.getColumnLabel(i + 1);
}
srs.first();
int zero = 0;
srs.last();
int numOfRows = srs.getRow();
if(numOfRows ==0){
if(directionForward){
jButton1.setEnabled(false);
}
else{
jButton2.setEnabled(false);
}
return;
}
else{
jButton1.setEnabled(true);
jButton2.setEnabled(true);
}
totalRowsDisplayed += numOfRows;
Object[][] data1 = new Object[numOfRows][columnNames.length];
srs.beforeFirst();
if (directionForward) {
int rowCount = 0;
while (srs.next() && rowCount < numOfRows) {
for (int i = 0; i < columnNames.length; i++) {
data1[rowCount] = srs.getObject(i + 1);
}
rowCount++;
}
}
else{
int rowCount = numOfRows-1;
while (srs.next() && rowCount < numOfRows) {
for (int i = 0; i < columnNames.length; i++) {
data1[rowCount][i] = srs.getObject(i + 1);
}
rowCount--;
}
}
maxRowIndex = (Integer) data1[numOfRows - 1][0];
minRowIndex = (Integer) data1[0][0];
DefaultTableModel model1 = new DefaultTableModel(data1, columnNames);
jTable1.setModel(model1);
} catch (Exception ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jNextButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//next
currentRowIndex = maxRowIndex;
directionForward = true;
printToTable();
}
private void jPreviousButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
currentRowIndex = minRowIndex;
directionForward = false;
printToTable();
//previous
}