码迷,mamicode.com
首页 > 数据库 > 详细

jdbc 分页

时间:2014-11-28 16:01:23      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

连接数据库

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();
        }
    }

}

 

jdbc 分页

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/Dreamlu/p/4128590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!