不废话直接上代码
1 public class Fenye { 2 static Connection conn = null; 3 static int count;//总行数 4 static{ 5 try { 6 Class.forName("com.mysql.jdbc.Driver"); 7 conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/xl", "root", "1234"); 8 PreparedStatement ps = conn.prepareStatement("SELECT CEIL(COUNT(id)/2) FROM user"); 9 ResultSet rs = ps.executeQuery(); 10 while(rs.next()){ 11 count = rs.getInt(1); 12 } 13 } catch (ClassNotFoundException e) { 14 e.printStackTrace(); 15 } catch (SQLException e) { 16 e.printStackTrace(); 17 } 18 19 } 20 public static List<User> getList(int index){ 21 List<User> list = new ArrayList<>(); 22 try { 23 String sql = "select id,name,age from user LIMIT ?,?"; 24 PreparedStatement ps= conn.prepareStatement(sql); 25 ps.setInt(1, (index-1)*2); 26 ps.setInt(2, 2); 27 ResultSet rs = ps.executeQuery(); 28 while(rs.next()){ 29 list.add(new User(rs.getInt("id"),rs.getString("name"),rs.getInt("age"))); 30 } 31 conn.close(); 32 return list; 33 } catch (SQLException e) { 34 e.printStackTrace(); 35 } 36 return list; 37 } 38 }
数据库插入5条数据,试试效果:
public static void main(String[] args) { System.out.println(getList(1).size());//第1页 查到2行 System.out.println(getList(2).size());//第2页 查到2行 System.out.println(getList(3).size());//第3页 查到1行 }
效果出来了
写的不好欢迎大家指教