欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 开发小工具: JDBC 连接及分页

程序员文章站 2024-01-20 16:52:22
...
package cn.archiect.taskOne.job02.beyond.test01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Author: beyond_nothing
 * @Date: 2021/4/27 9:36
 */
public class SqlTest {
    public static final String DRIVERNAME = "com.mysql.cj.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/test";
    public static final String USER = "root";
    public static final String PASSWORD = "q210374520";

    public static void main(String[] args) throws Exception {
        Class.forName(DRIVERNAME);
        int currentPage = 2; // 当前第1页
        int lineSize = 5;  // 每页显示5行
        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
        System.out.println(connection);
        String cname = "1";
        String sql = " SELECT cid, cname,cteacher FROM class_main where cname like ?  " +
                " limit ?,?";
        PreparedStatement pstat = connection.prepareStatement(sql);
        pstat.setString(1, "%" + cname + "%");
        pstat.setInt(2, (currentPage - 1) * lineSize);
        pstat.setInt(3, lineSize);
        ResultSet res = pstat.executeQuery();
        while (res.next()) {
            int cid = res.getInt(1);
            cname = res.getString(2);
            String cteacher = res.getString(3);
            System.out.println(cid + ", " + cname + "," + cteacher + "," + cteacher + ".");
        }


    }
}

Java 开发小工具: JDBC 连接及分页