JDBC之分页查询

limit [位置偏移量,] 行数
位移偏移量是指从哪一行开始(行数从0开始)
行数为向下取几行

第几页与从哪一行开始是有联系的

 在表格中的起始行数= (第几页-1*每页的行数

行数也可指为每页有多少行

以下为代码例子:

	public static void main(String[] args) {
		selectUserByPage(6, 5);//表示按每页5行要查询第6页
	}
	
	public static void selectUserByPage(int pageNumber,int pageCount)//两个参数分别指,第几页和每页的行数
	{
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");//使用什么驱动连接数据库
			String url="jdbc:mysql://localhost:3306/hahahhha?useUnicode=true&characterEncoding=UTF8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT";
			String user="root";
			String password="password";
			con=DriverManager.getConnection(url,user,password);
			String sql="select * from student limit ?,?";//此处参数设置为?
			pstmt=con.prepareStatement(sql);
			pstmt.setInt(1,(pageNumber-1)*pageCount);//此处再对?进行设置
			//根据那个student表起始行与页数的关系
			pstmt.setInt(2,pageCount);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getInt(3));
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
				try {
					if(rs!=null) rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				try {
					if(pstmt!=null) pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				try {
					if(con!=null) con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

猜你喜欢

转载自blog.csdn.net/henulmh/article/details/105045016