java swing 连接数据库分页代码
时间: 2023-09-10 21:05:43 浏览: 168
Java SE程序 连接数据库的分页
以下是一个简单的Java Swing连接数据库并实现分页的示例代码:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class DatabasePaginationExample extends JFrame {
private static final long serialVersionUID = 1L;
private static final int PAGE_SIZE = 10;
private Connection conn;
private int currentPage = 1;
private int totalRows;
private int totalPages;
private JTable table;
private DefaultTableModel model;
public DatabasePaginationExample() {
setTitle("Database Pagination Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
setLocationRelativeTo(null);
String[] columnNames = {"Name", "Age", "Gender"};
model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
add(new JScrollPane(table));
connectToDatabase();
loadPage(currentPage);
setVisible(true);
}
private void connectToDatabase() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
private void loadPage(int page) {
try {
String countQuery = "SELECT COUNT(*) FROM employees";
PreparedStatement countStmt = conn.prepareStatement(countQuery);
ResultSet countResult = countStmt.executeQuery();
countResult.next();
totalRows = countResult.getInt(1);
totalPages = (int) Math.ceil((double) totalRows / PAGE_SIZE);
model.setRowCount(0);
String query = "SELECT * FROM employees LIMIT ?,?";
PreparedStatement stmt = conn.prepareStatement(query);
int offset = (page - 1) * PAGE_SIZE;
stmt.setInt(1, offset);
stmt.setInt(2, PAGE_SIZE);
ResultSet result = stmt.executeQuery();
while (result.next()) {
String name = result.getString("name");
int age = result.getInt("age");
String gender = result.getString("gender");
model.addRow(new Object[]{name, age, gender});
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
public static void main(String[] args) {
new DatabasePaginationExample();
}
}
```
以上代码使用了MySQL数据库作为示例。你需要改变数据库驱动程序的名称、URL、用户名和密码以适应你自己的情况。
在 `loadPage` 方法中,第一个查询获取表的总行数,第二个查询使用 `LIMIT` 和 `OFFSET` 子句来获取当前页的数据行。`offset` 值是当前页数减一乘以每页的行数,它用于计算要跳过的行数。数据检索后,将其添加到表格模型中。
`connectToDatabase` 方法创建了一个 `Connection` 对象,它与数据库建立连接。
在 `main` 方法中,创建了一个 `DatabasePaginationExample` 对象,它创建了一个带有滚动条的表格和两个按钮。每次单击下一页按钮时,当前页面计数器 `currentPage` 增加,然后重新加载该页面。如果尝试加载当前页面之外的页面,会发出警告。
阅读全文