2016-03-31 105 views
0

是否有一個很好的示例,說明如何使用Apache Derby實現分頁,以便每次選擇新頁面時都不返回整個結果集?使用Apache Derby進行分頁

如果查詢可以按用戶指定的列進行排序,這也會有所幫助。

回答

1

這些都是德比的關鍵字,幫助實現分頁時:OFFSET and FETCH

用法示例:

//all these values are supplied by the GUI 
int rowsPerPage = 10; 
int pageNumber = 3; 
String columnToSortBy = "first_name"; //this value should never be directly edited by the user. Otherwise it could be used for sql injection 

StringBuilder statement = new StringBuilder(); 
statement.append("select * from users\n"); 
statement.append("order by " + columnToSortBy + "\n"); 
statement.append("offset ? rows fetch first ? rows only"); 

try (PreparedStatement ps = conn.prepareStatement(statement.toString())) { 

    ps.setInt(1, pageNumber * rowsPerPage); 
    ps.setInt(2, rowsPerPage); 

    ResultSet rs = ps.executeQuery(); 
    printResultSet(rs); 
} 

一個更復雜的例子:

//all these values are supplied by the GUI 
int rowsPerPage = 10; 
int pageNumber = 3; 
String columnToSortBy = "first_name"; //this value should never be directly edited by the user. Otherwise it could be used for sql injection 

String selectClause = "select * from users\n"; 
String whereClause = "where first_name like ?"; 
String orderClause = "order by " + columnToSortBy + "\n"; 
String limitClause = "offset ? rows fetch first ? rows only"; 

//build the sql statement 
String statement = ""; 
statement += selectClause; 
statement += whereClause; 

//get the total rows 
int totalRows = 0; 
try (PreparedStatement ps = conn.prepareStatement(statement)) { 
    ps.setString(1, "Sam%"); 

    ResultSet rs = ps.executeQuery(); 
    while (rs.next()) { 
     totalRows++; 
    } 
} 
System.out.println(totalRows + " total rows\n");   

//change the statement to use pagination 
statement += orderClause; 
statement += limitClause; 

//get the 3rd page 
try (PreparedStatement ps = conn.prepareStatement(statement)) { 

    ps.setString(1, "Sam%"); 
    ps.setInt(2, pageNumber * rowsPerPage); 
    ps.setInt(3, rowsPerPage); 

    ResultSet rs = ps.executeQuery(); 
    printResultSet(rs); 
} 

System.out.println("\nNext page\n"); 

//get the 4th page 
try (PreparedStatement ps = conn.prepareStatement(statement)) { 

    ps.setString(1, "Sam%"); 
    ps.setInt(2, (pageNumber + 1) * rowsPerPage); 
    ps.setInt(3, rowsPerPage); 

    ResultSet rs = ps.executeQuery(); 
    printResultSet(rs); 
} 
+1

感謝很好寫的例子!另見http://stackoverflow.com/questions/19606571/derby-db-sql-select-rows-starting-from-row-number/19606655#19606655 –