jdbc 分页

连接数据库

public class DbUtil {
    private String driver = "oracle.jdbc.OracleDriver";
    private String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
    private String user = "system";
    private String password = "FengZe2012";
    private Connection conn = null;

    public DbUtil() {
        try {
            Class.forName(this.driver);
            this.conn = DriverManager.getConnection(this.url, this.user, this.password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getConn() {
        return this.conn;
    }
}

分页查询

public class PagerDemo {
    public static void main(String[] args) {
        DbUtil du = new DbUtil();
        Connection conn = du.getConn();
        try {
            String sql = "select count(*) from stu";
            PreparedStatement pst1 = conn.prepareStatement(sql);
            ResultSet rs1 = pst1.executeQuery();
            rs1.next();
            int recordcount = rs1.getInt(1); //统计总记录数
            pst1.close();
            
            int pagesize = 3; //指定每页多少条
            //算出总页数
            int pagecount = recordcount%pagesize==0 ? recordcount/pagesize : recordcount/pagesize+1;

            sql = "select * from (select s.*,rownum rn from stu s) where rn between ? and ?";
            PreparedStatement pst2 = conn.prepareStatement(sql);
            
            int p = -6;
            p = p < 1 ? 1 : p;
            p = p >= pagecount ? pagecount : p;
            pst2.setInt(1,p*pagesize-pagesize+1);
            pst2.setInt(2,pagesize*p);
            pst2.execute();
            
            ResultSet rs = pst2.executeQuery();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss S");
            while(rs.next()){
                System.out.println(rs.getString("sname")+"    "+sdf.format(rs.getDate("sbirthday")));
            }
            //PreparedStatement pst = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。