您的位置:首页 > 编程语言 > Java开发

java连接数据库分页问题

2016-05-19 10:13 204 查看
1.数据库 的 数据 传到 java 中 需要 做到 分页

我们来 看看 有几种 方法

---- 1. 上一页 2.下一页 3 尾页 4. 第一页

------ 第一页 第二页 第三页 第四页 第五页

——————————————————————————

实现 第一种的 做法 就是

2. 你要知道 :你有多少行

你需要知道一页上显示多少列

需要 显示第几页

@Override

// 这是 写在
实现了 接口的 那个类中的 方法

public int GetRowCount() throws SQLException {

String sql ="select count(1) cnt from product";

ResultSet rst = db.GetResultSet(sql);

int rowcount=-1;

while(rst.next()){

rowcount=rst.getInt("cnt");

}

rst.close();

db.CloseAll();

return rowcount;

}

@Override

显示第几页 显示多少 行

public List<Product> GetPageList(int currentPageNo, int pageSize)

throws SQLException {

String sql="select top "+pageSize+" * from product

where id not in (select

top "+pageSize*(currentPageNo-1)+"

id from product order by id asc ) order by id asc";

ResultSet rst = db.GetResultSet(sql);

List<Product> list=new ArrayList<Product>();

Product entity=null;

while(rst.next()){

int id=rst.getInt("id");

String name=rst.getString("name");

String unit=rst.getString("unit");

double price =rst.getDouble("price");

int count=rst.getInt("count");

entity=new Product(id, name, unit, price, count);

list.add(entity); 就是 每次 得到一个对象,就直接 放到 list 里面

}

rst.close();

db.CloseAll();

return list;

}

——————————————————————

3. 写完了 与数据库 的 连接的 部分,然后就是

view 部分

3.1首先 就是 打印 数据的部分

public static void PrintPageList(int currentPageNo,int pageSize) throws SQLException{

IProductDao dao=new ProductDaoimpl();

List<Product> list=dao.GetPageList(currentPageNo, pageSize);

System.out.println("编号\t名称\t单位\t单价\t库存数量");

for(Product m : list){

System.out.print(m.getId()+"\t");

System.out.print(m.getName()+"\t");

System.out.print(m.getUnit()+"\t");

System.out.print(m.getPrice()+"\t");

System.out.println(m.getCount()+"\t");

}

}

然后就是 实际 的操作 部分的 编写

Scanner input = new Scanner(System.in);

IProductDao dao=new ProductDaoimpl();

// 设置 参数的 部分

int pageSize=3;// 默认 的 一页显示3行

int currentPageNo=1; 默认 先显示第一页

int rowcount=dao.GetRowCount(); 获得 总行数

设置 总的 页数

int totalpage=rowcount%pageSize==0?rowcount/pageSize:rowcount/pageSize+1;

打印第一页

PrintPageList(currentPageNo,pageSize);

while(true){

System.out.println("请选择1.第一页;2.上一页;3.下一页;4.尾页");

int choice=input.nextInt();输入 你的选择

boolean flag=false;

switch(choice){

case 1:

currentPageNo=1;

PrintPageList(currentPageNo,pageSize);

break;

case 2:
选择的 上一页, 必须 当前页面不在 第一页

if(currentPageNo>1){

currentPageNo=currentPageNo-1;

}

PrintPageList(currentPageNo,pageSize);

break;

case 3:

if(currentPageNo<totalpage){

currentPageNo=currentPageNo+1;

}

PrintPageList(currentPageNo,pageSize);

break;

case 4:

currentPageNo=totalpage;

PrintPageList(currentPageNo,pageSize);

break;

default:

flag=true;

break;

}

if(flag){

System.out.println("选择了退出操作。。。");

break;

}

}

大概 的情况就是这样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: