以下是Java MySQL分页查询的示例代码:

import java.sql.*;

public class MySQLPaginationExample {
    
    public static void main(String[] args) {
        
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "myusername";
        String password = "mypassword";
        
        int page = 2; // page number
        int pageSize = 10; // number of records per page
        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
            stmt = conn.createStatement();
            
            // calculate the offset
            int offset = (page - 1) * pageSize;
            
            // execute the query with limit and offset
            String sql = "SELECT * FROM mytable LIMIT " + pageSize + " OFFSET " + offset;
            rs = stmt.executeQuery(sql);
            
            // process the result set
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
            }
            
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // close the resources
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

在上面的示例中,我们使用了LIMITOFFSET来执行MySQL分页查询。LIMIT用于指定每页记录数,OFFSET用于指定从哪一行开始查询。pagepageSize变量用于计算偏移量。

请确保在使用该代码之前替换你的MySQL数据库URL、用户名和密码。

java写一个mysql分页查询

原文地址: https://www.cveoy.top/t/topic/Mlr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录