package com.basicSql.scroll_page;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.basicSql.connUtil.Conndb;
/**
* 数据库的分页显示
*
* @author xrhou
*
*/
public class PageSplit {
private static Connection conn = null;
private static Statement stmt = null;
private static PreparedStatement pStmt = null;
private static ResultSet rs=null;
public static void main(String[] args) {
getPage(10, 1);
System.out.println("========================");
getPageSimple(10,-4);
}
/**
* 取得表的总行数
* @return
*/
public static int getTotalNumber(){
int n=-1;
String sql="select count(*) num from t_student ";
try {
conn=Conndb.connOracle();
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
rs.next();
n=rs.getInt("num");
} catch (SQLException e) {
e.printStackTrace();
}
//System.out.println(n);
return n;
}
public static void getPageSimple(int pageSize, int page) {
// totalPage:总页数 totalNumber:总记录条数
int totalPage = 0;
int totalNumber = getTotalNumber();
if (totalNumber % pageSize == 0) {
totalPage = totalNumber / pageSize;
} else {
totalPage = totalNumber / pageSize + 1;
}
if (page > totalPage) {
page = totalPage;
}
if (page < 1) {
page = 1;
}
int from=(page-1)*pageSize+1;
int to=from+pageSize;
getResult(from, to);
}
/**
* 分页
*
* @param pageSize
* @param page
*/
public static void getPage(int pageSize, int page) {
int from =(page-1)*pageSize+1;
int to=from+pageSize;
String sql = "select id,name,age,rn "
+ " from (select id,name,age,rownum rn from t_student "
+ "where rownum<?) "
+ "where rn>=?";
try {
conn = Conndb.connOracle();
pStmt = conn.prepareStatement(sql);
pStmt.setInt(1, to);
pStmt.setInt(2, from);
rs = pStmt.executeQuery();
while (rs.next()) {
String line = rs.getInt("id") + "---" + rs.getString("name")
+ "---" + rs.getInt("age")+"---"+rs.getInt("rn");
System.out.println(line);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
Conndb.rsClose(rs);
Conndb.pStmtClose(pStmt);
Conndb.closeConn(conn);
}
}
/**
* 分条
*
* @param m
* @param n
*/
public static void getResult(int m, int n) {
String sql = "select id,name,age,rn "
+ " from (select id,name,age,rownum rn from t_student "
+ "where rownum<?) "
+ "where rn>=?";
try {
conn = Conndb.connOracle();
pStmt = conn.prepareStatement(sql);
pStmt.setInt(1, n);
pStmt.setInt(2, m);
ResultSet rs = pStmt.executeQuery();
while (rs.next()) {
String line = rs.getInt("id") + "---" + rs.getString("name")
+ "--" + rs.getDouble("age")+"--"+rs.getInt("rn");
System.out.println(line);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}