SqlServer数据库中使用top分页

//分页检索数据   
    public List getDataSplit(String table,String orderCoulmn,String condition,int page,int pageCount){   
        long start = System.currentTimeMillis();   
        List list = new ArrayList();   
        Connection conn = this.getConn();   
        Statement stmt = null;   
        ResultSet rs = null;   
           
        String orderby = "order by zj";//默认   
        if(orderCoulmn!=null && !orderCoulmn.trim().equals(""))orderby = orderby.replace("zj",orderCoulmn);   
        if(condition!=null && !condition.trim().equals(""))condition = " and "+condition;   
           
        try {   
            stmt = conn.createStatement();   
            rs = stmt.executeQuery("select count(*) from "+table+" where 1=1 "+condition);   
            rs.next();   
            int count = rs.getInt(1);   
            list.add(new Integer(count));//把总数加入到结果集中   
            if(page <=0)page=1;   
            int number = (page-1)*pageCount;   
            if(number > count)number = (count-pageCount+1)/pageCount  ;   
               
//          String sql = "select top "+pageCount+" * from "+table+" where ("+orderCoulmn+" not in (select top "+number+" "+orderCoulmn+" FROM "+table+" where 1=1 "+condition+" "+orderby+")) "+condition+" "+orderby;   
            String sql = "select top "+pageCount+" * from "+table+" where (zj not in (select top "+number+" zj FROM "+table+" where 1=1 "+condition+" "+orderby+")) "+condition+" "+orderby;   
//          System.out.println(sql+"\n");   
            rs = stmt.executeQuery(sql);   
               
            int length = rs.getMetaData().getColumnCount();   
            while(rs.next()){   
                Map map = new HashMap();   
                for (int i = 1; i <= length; i++) {   
                    Object value = rs.getObject(i);   
                    value=value==null?"":value;   
                    map.put(rs.getMetaData().getColumnName(i).toLowerCase(),new String(value.toString().getBytes("ISO-8859-1"),"GBK"));//可能需要转码   
                }   
                   
                list.add(map);   
            }   
            rs.close();   
            stmt.close();   
        } catch (Exception e) {   
            e.printStackTrace();   
            NetSystem.log.log(e.getLocalizedMessage());   
            try {   
                if(rs != null)   
                    rs.close();   
                if(stmt != null)   
                    stmt.close();   
            } catch (Exception e1) {}   
        }finally{   
            this.freeConnection();   
        }   
        long end = System.currentTimeMillis();   
        //50W数据量,主键建立聚集索引,此方法耗时基本在0.219-1.188之间(个人电脑配置)   
//      System.out.println("耗时: "+(end-start)+" 毫秒"+"  秒:"+(end-start)/1000f);   
        return list;   
    }  

你可能感兴趣的:(sql)