MySQL存储过程分页兼返回总页数
因为MySQL目前不支持动态参数分页所以存储过程中要么传sql语句过去要么自己写个字符串连接方法
下为第二种方法
把每个需要分割的地方单写一行,清除
- BEGIN
- SELECT CEIL(COUNT(*)/pageNum) INTO pageCount FROM mytestdb.mttest WHERE tt_id = arg_mt_id;
- SET @sqlStr = CONCAT('SELECT `mt_id`,`tt_id`,`tt_name` FROM `mytestdb`.`mttest` WHERE `tt_id` = ');
- SET @sqlStr = CONCAT(@sqlStr,arg_mt_id);
- SET @sqlStr = CONCAT(@sqlStr,' LIMIT ');SET @sqlStr = CONCAT(@sqlStr,((pageNum-1)*pageSize));
- SET @sqlStr = CONCAT(@sqlStr,',');
- SET @sqlStr = CONCAT(@sqlStr,pageSize);
- SET @sqlStr = CONCAT(@sqlStr,';');
- PREPARE s1 FROM @sqlStr;
- EXECUTE s1;
- DEALLOCATE PREPARE s1;
- END
或者写成一行,效率高但是更容易写错
- BEGIN
- SELECT CEIL(COUNT(*)/pageNum) INTO pageCount FROM mytestdb.mttest WHERE tt_id = arg_mt_id;
- SET @sqlStr = CONCAT('SELECT `mt_id`,`tt_id`,`tt_name` FROM `mytestdb`.`mttest` WHERE `tt_id` = ',arg_mt_id,' LIMIT ',
- ((pageNum-1)*pageSize),',',pageSize';');
- PREPARE s1 FROM @sqlStr;EXECUTE s1;DEALLOCATE PREPARE s1;END
java端
- try {Connection conn = db.openDB(getServletContext());String sql = "{call `myPagingTest`(?,?,?,?)}";CallableStatement cs = conn.prepareCall(sql);cs.setInt(1, 1);cs.setInt(2, 1);cs.setInt(3, 5);cs.registerOutParameter(4, Types.INTEGER);rs = cs.executeQuery();System.out.println(cs.getInt(4));while(rs.next()){out.println(rs.getInt(1)); out.println(rs.getInt(2)); out.println(rs.getString(3) + "<br>"); }} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{ try {if(rs != null){rs.close();}if(db!=null){db.close();}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20