时隔多年,我又有了新的课设任务,还是最原始的基于swing的管理系统(前几天还做了个纯控制台打印的,人给做麻了,忘记放上来了,明天放,至少记录一下废物工作日常)。
先放项目目录,我的代码不正规也不简洁,主打一个冗余但自己能看懂,希望代码警察不要审判我。
环境配置
IDEA里自带了swing插件,新建一个项目,然后new一个GUI窗体就好了,或者自己纯写界面也可以,我瞎写的,我没有审美,我还懒,不乐意用插件。
然后把jdbc的包放进lib文件夹里:
环境也就配置好了 。
JDBC连接mysql
public DBOper() {
try {
// 连接数据库
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
mysql中建表
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT,
gender VARCHAR(10)
);
所有代码
dao层,直接对数据库进行操作,这里我没有封装。
package dao;
import javax.swing.*;
import java.sql.*;
public class DBOper {
private Connection connection;
public DBOper() {
try {
// 连接数据库
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addStudent(String name, int age, String gender) {
String query = "INSERT INTO students (name, age, gender) VALUES (?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(query)) {
System.out.println("添加成功!"+name+age+gender);
statement.setString(1, name);
statement.setInt(2, age);
statement.setString(3, gender);
JOptionPane.showMessageDialog(null, "添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateStudent(int id, String name, int age, String gender) {
String query = "UPDATE students SET name = ?, age = ? , gender = ? WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, name);
statement.setInt(2, age);
statement.setString(3, gender);
statement.setInt(4, id);
JOptionPane.showMessageDialog(null, "修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteStudent(int id) {
String query = "DELETE FROM students WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setInt(1, id);
// int x;
statement.executeUpdate();
// x = statement.executeUpdate();
// System.out.println("xxxxxx"+x);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Object[][] getAllStudents() {
Statement stmt = null;
ResultSet rs = null;
Object[][] result = null;
try {
stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT * FROM students");
// 获取 ResultSet 的行数
rs.last();
int rowCount = rs.getRow();
// 将 ResultSet 指针移到第一行
rs.beforeFirst();
// 初始化结果数组
result = new Object[rowCount][4];
// 遍历 ResultSet 并填充结果数组
int i = 0;
while (rs.next()) {
result[i][0] = rs.getInt(1); // ID
result[i][1] = rs.getString(2); // name
result[i][2] = rs.getInt(3); // age
result[i][3] = rs.getString(4); // gender
i++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public Object[][] searchById(int id) {
try {
String query = "SELECT * FROM students WHERE id = ?";
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if(resultSet==null){
JOptionPane.showMessageDialog(null, "当前查询学号不存在!", "错误", JOptionPane.ERROR_MESSAGE);
resultSet.close();
statement.close();
}else{
// 统计结果集中的行数
int rowCount = 0;
if (resultSet.last()) {
rowCount = resultSet.getRow();
resultSet.beforeFirst(); // 将结果集指针重置到第一行之前
}
Object[][] results = new Object[rowCount][4];
int row = 0;
while (resultSet.next()) {
results[row][0] = resultSet.getInt("id");
results[row][1] = resultSet.getString("name");
results[row][2] = resultSet.getInt("age");
results[row][3] = resultSet.getString("gender");
row++;
}
// System.out.println(results[0][0]);
// 关闭结果集和语句对象
resultSet.close();
statement.close();
return results;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Object[][] searchByGender(String gender) {
try {
String query = "SELECT * FROM students WHERE gender = ?";
// PreparedStatement statement = connection.prepareStatement(query);
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
statement.setString(1, gender);
// String query = "SELECT * FROM students WHERE id = ?";
// statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
// 统计结果集中的行数
int rowCount = 0;
if (resultSet.last()) {
rowCount = resultSet.getRow();
resultSet.beforeFirst(); // 将结果集指针重置到第一行之前
}
Object[][] results = new Object[rowCount][4]; // 假设每个学生有 4 个属性
// 逐行读取结果集中的数据并存储在二维数组中
int row = 0;
while (resultSet.next()) {
results[row][0] = resultSet.getInt("id");
results[row][1] = resultSet.getString("name");
results[row][2] = resultSet.getInt("age");
results[row][3] = resultSet.getString("gender");
row++;
}
// 关闭结果集和语句对象
resultSet.close();
statement.close();
return results;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void close() {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ui,界面
主界面:StudentManagementUI
package ui;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import dao.DBOper;
public class StudentManagementUI extends JFrame {
private JTable table;
private JTextField txtId, txtName, txtAge, txtGender, searchMsg;
private JButton btnAdd, btnUpdate, btnDelete, btnIncreaseAge, btnDecreaseAge, btnSearchById, btnSearchByGender, returnButton, addButton, modifyButton;
private DBOper dbOper;
private DefaultTableModel tableModel;
private JPopupMenu popupMenu;
public StudentManagementUI() {
dbOper = new DBOper();
setTitle("学生管理系统");
setLayout(new BorderLayout(5, 5));
// 表格初始化
String[] columnNames = {"ID", "姓名", "年龄", "性别"};
tableModel = new DefaultTableModel(columnNames, 0);
// 从数据库获取学生信息并添加到表格中
Object[][] students = dbOper.getAllStudents();
for (Object[] student : students) {
tableModel.addRow(student);
}
table = new JTable(tableModel);
add(new JScrollPane(table), BorderLayout.CENTER);
// 创建右键菜单
popupMenu = new JPopupMenu();
JMenuItem deleteMenuItem = new JMenuItem("删除");
popupMenu.add(deleteMenuItem);
// 将右键菜单添加到表格中
table.setComponentPopupMenu(popupMenu);
// 控制面板用于添加、更新和删除操作
JPanel controlPanel = new JPanel(new FlowLayout());
add(controlPanel, BorderLayout.SOUTH);
JPanel searchPanel = new JPanel(new FlowLayout());
searchMsg = new JTextField(10);
returnButton = new JButton("返回");
btnSearchById = new JButton("按id查询");
btnSearchByGender = new JButton("按性别查询");
searchPanel.add(btnSearchById);
searchPanel.add(btnSearchByGender);
searchPanel.add(searchMsg);
searchPanel.add(returnButton);
// addButton = new JButton("新增");
// searchPanel.add(addButton);
controlPanel.add(new JLabel("searchMsg"));
add(searchPanel, BorderLayout.NORTH);
// addButton = new JButton("新增");
// add(addButton, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout());
addButton = new JButton("新增");
modifyButton = new JButton("修改");
btnIncreaseAge = new JButton("增加年龄");
btnDecreaseAge = new JButton("减少年龄");
buttonPanel.add(addButton);
buttonPanel.add(modifyButton);
buttonPanel.add(btnIncreaseAge);
buttonPanel.add(btnDecreaseAge);
add(buttonPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
deleteMenuItem.addActionListener(e -> deleteSelectedRow());
btnIncreaseAge.addActionListener(e -> changeAddAge('+'));
btnDecreaseAge.addActionListener(e -> changeAddAge('-'));
btnSearchById.addActionListener(e -> searchById());
btnSearchByGender.addActionListener(e -> searchByGender());
returnButton.addActionListener(e -> returnToMain());
addButton.addActionListener(e -> returnToAdd());
modifyButton.addActionListener(e -> modifyInput());
}
void returnToMain(){
searchMsg.setText("");
Object[][] students = dbOper.getAllStudents();
tableModel.setRowCount(0);
// 将查询结果更新到表格中
for (Object[] student : students) {
tableModel.addRow(student);
}
}
private void deleteSelectedRow() {
int selectedRow = table.getSelectedRow();
System.out.println("getid"+selectedRow);
if (selectedRow >= 0) {
int id = (int) tableModel.getValueAt(selectedRow, 0);
dbOper.deleteStudent(id);
returnToMain();
}
}
private void changeAddAge(char c) {
int selectedRow = table.getSelectedRow();
System.out.println("getid"+selectedRow);
if (selectedRow >= 0) {
int id = (int) tableModel.getValueAt(selectedRow, 0); // 获取选中行的ID
Object[][] students = dbOper.searchById(id);
new changeAgeUI(this,students[0],c);
returnToMain();
}else {
System.out.println("没选择!!!!!!!!");
JOptionPane.showMessageDialog(null, "请在表格中选择需要修改年龄的学生!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void returnToAdd(){
new addStudentUI(this);
}
private void modifyInput() {
if(searchMsg.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "输入框不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
}
else{
if(searchMsg.getText().matches("\\d+")){
int id = Integer.parseInt(searchMsg.getText());
System.out.println("点击修改按钮了!!!");
Object[][] students = dbOper.searchById(id);
if(students.length == 0) {
System.out.println("学号不存在!!!!!!");
JOptionPane.showMessageDialog(null, "当前查询学号不存在!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
} else {
System.out.println("主界面的modifyInput "+students[0][0]);
new modifyStudentUI(this, students[0]); // 注意这里传递的是单个学生数据
}
}
else {
JOptionPane.showMessageDialog(null, "输入错误!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
}
}
}
private void searchById() {
if(searchMsg.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "查询信息不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
}
else if (searchMsg.getText().matches("\\d+")){
int id = Integer.parseInt(searchMsg.getText());
Object[][] students = dbOper.searchById(id);
if (students.length == 0 || students[0].length == 0 || students[0][0].toString().isEmpty()){
JOptionPane.showMessageDialog(null, "当前查询学号不存在!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
}
else{
// 清空表格数据
tableModel.setRowCount(0);
// 将查询结果更新到表格中
for (Object[] student : students) {
tableModel.addRow(student);
}
searchMsg.setText("");
}
}
else{
JOptionPane.showMessageDialog(null, "输入错误!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
}
}
private void searchByGender() {
if(searchMsg.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "查询信息不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
}
else {
String gender = searchMsg.getText();
if(gender.contains("男")||gender.contains("女")){
Object[][] students = dbOper.searchByGender(gender);
if(students==null){
JOptionPane.showMessageDialog(null, "当前查询性别不存在!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
}
else {
tableModel.setRowCount(0);
for (Object[] student : students) {
tableModel.addRow(student);
}
}
}else{
JOptionPane.showMessageDialog(null, "输入错误!", "错误", JOptionPane.ERROR_MESSAGE);
searchMsg.setText("");
}
}
}
public static void main(String[] args) {
new StudentManagementUI();
}
}
新增学生弹出界面:addStudentUI
package ui;
import javax.swing.*;
import dao.DBOper;
public class addStudentUI extends JDialog {
private JLabel nameLab,genderLab,ageLab;
private JTextField nameVal,ageVal,genderVal;
private JComboBox genderBox;
private JButton button;
private DBOper dbOper = new DBOper();
private StudentManagementUI mainFrame;
public addStudentUI(StudentManagementUI mainFrame) {
this.mainFrame = mainFrame;
setTitle("新增学生");
setLayout(null);
nameLab = new JLabel("姓名:");
genderLab = new JLabel("性别:");
ageLab = new JLabel("年龄:");
nameVal = new JTextField();
genderBox=new JComboBox();
ageVal= new JTextField();
button = new JButton("确定");
//向性别下拉菜单中填充内容
String[] sexs = {"男","女"};
for (int i = 0; i < sexs.length; i++) {
genderBox.addItem(sexs[i]);
}
// 设置位置
nameLab.setBounds(20,50,60,20);
genderLab.setBounds(20,80,60,20);
ageLab.setBounds(20,110,60,20);
nameVal.setBounds(80,50,100,20);
genderBox.setBounds(80,80,100,20);
ageVal.setBounds(80,110,100,20);
button.setBounds(60,260,100,20);
add(nameLab);
add(genderLab);
add(ageLab);
add(nameVal);
add(genderBox);
add(ageVal);
add(button);
button.addActionListener(e -> addStudent());
setBounds(0, 3, 260, 400);
setLocationRelativeTo(null);
setVisible(true);
}
private void addStudent() {
if(nameVal.getText().isEmpty()||ageVal.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "姓名和年龄不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
}
else{
String name = nameVal.getText();
int age = Integer.parseInt(ageVal.getText());
if(age<=10||age>=80){
JOptionPane.showMessageDialog(null,"年龄错误!年龄应在[10,80]区间,请重新输入!","提示消息",JOptionPane.ERROR_MESSAGE);
ageVal.setText("");
}
else{
String gender = (String) genderBox.getSelectedItem();
dbOper.addStudent(name, age, gender);
mainFrame.returnToMain();
dispose();
}
}
// String gender = genderVal.getText();
}
public static void main(String[] args) {
StudentManagementUI mainFrame = new StudentManagementUI();
new addStudentUI(mainFrame);
}
}
修改学生信息弹出界面:modifyStudentUI
package ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import dao.DBOper;
public class modifyStudentUI extends JDialog {
private JLabel idLab, nameLab, genderLab, ageLab;
private JTextField idVal, nameVal, ageVal;
private JComboBox<String> genderBox;
private JButton button;
private DBOper dbOper = new DBOper();
private StudentManagementUI mainFrame;
private Object[] students;
public modifyStudentUI(StudentManagementUI mainFrame, Object[] students) {
this.students = students;
System.out.println("sssss"+students[0]);
System.out.println("sssss1"+students[1]);
System.out.println("sssss2"+students[2]);
System.out.println("sssss3"+students[3]);
this.mainFrame = mainFrame;
setTitle("修改学生信息");
setLayout(null);
idLab = new JLabel("学号");
nameLab = new JLabel("姓名:");
genderLab = new JLabel("性别:");
ageLab = new JLabel("年龄:");
idVal = new JTextField();
nameVal = new JTextField();
genderBox = new JComboBox<>();
ageVal = new JTextField();
button = new JButton("确定");
// 向性别下拉菜单中填充内容
genderBox.addItem("男");
genderBox.addItem("女");
// 设置位置
idLab.setBounds(20, 20, 60, 20);
nameLab.setBounds(20, 50, 60, 20);
genderLab.setBounds(20, 80, 60, 20);
ageLab.setBounds(20, 110, 60, 20);
idVal.setBounds(80, 20, 100, 20);
nameVal.setBounds(80, 50, 100, 20);
genderBox.setBounds(80, 80, 100, 20);
ageVal.setBounds(80, 110, 100, 20);
button.setBounds(60, 260, 100, 20);
add(idLab);
add(idVal);
add(nameLab);
add(genderLab);
add(ageLab);
add(nameVal);
add(genderBox);
add(ageVal);
add(button);
displayStudentInfo();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = Integer.parseInt(String.valueOf(students[0]));
modifyStudent(id);
// displayStudentInfo();
}
});
setBounds(0, 3, 260, 400);
setLocationRelativeTo(null);
setVisible(true);
}
// private Object[][] getStudentInfo(Object[][] students, int id) {
// for (Object[][] student : students) {
// if ((int) student[0][0] == id) {
// return student;
// }
// }
// return null;
// }
private void displayStudentInfo() {
idVal.setText(students[0].toString());
idVal.setEditable(false);
nameVal.setText(students[1].toString());
genderBox.setSelectedItem((String) students[3]);
ageVal.setText(String.valueOf(students[2]));
}
private void modifyStudent(int id) {
Object[] studentInfo = dbOper.searchById(id);
if (studentInfo != null) {
if(nameVal.getText().isEmpty()||ageVal.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "姓名和年龄不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
}
else{
String name = nameVal.getText();
int age = Integer.parseInt(ageVal.getText());
String gender = (String) genderBox.getSelectedItem();
if(age<=10||age>=80){
JOptionPane.showMessageDialog(null,"年龄错误!年龄应在[10,80]区间,请重新输入!","提示消息",JOptionPane.ERROR_MESSAGE);
ageVal.setText("");
}
else{
dbOper.updateStudent(id, name, age, gender);
mainFrame.returnToMain();
dispose();
}
}
} else {
JOptionPane.showMessageDialog(null, "学号不存在!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
public void main(String[] args) {
StudentManagementUI mainFrame = new StudentManagementUI();
new modifyStudentUI(mainFrame, this.students);
}
}
修改选中行年龄弹出界面:changeAgeUI
package ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import dao.DBOper;
public class changeAgeUI extends JDialog {
private JLabel idLab, nameLab, genderLab, changeAgeLab;
private JTextField idVal, nameVal, changeAgeVal;
private JComboBox<String> genderBox;
private JButton button;
private DBOper dbOper = new DBOper();
private StudentManagementUI mainFrame;
private Object[] students;
private char symbol;
public changeAgeUI(StudentManagementUI mainFrame, Object[] students, char symbol) {
this.students = students;
// System.out.println("sssss"+students[0]);
// System.out.println("sssss1"+students[1]);
// System.out.println("sssss2"+students[2]);
// System.out.println("sssss3"+students[3]);
System.out.println("sssss3"+symbol);
this.mainFrame = mainFrame;
setTitle("请输入要修改的年龄:");
setLayout(null);
changeAgeVal = new JTextField(10);
button = new JButton("确定");
// 设置位置
changeAgeVal.setBounds(20, 30, 145, 30);
button.setBounds(40, 100, 100, 20);
add(changeAgeVal,BorderLayout.CENTER);
add(button,BorderLayout.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = Integer.parseInt(String.valueOf(students[0]));
modifyStudent(id,symbol);
}
});
setBounds(0, 3, 200, 180);
setLocationRelativeTo(null);
setVisible(true);
}
private void modifyStudent(int id,char symbol) {
int age = (int)students[2];
int age1 = 0;
System.out.println("ageeeeeeeeeeee"+age);
if(changeAgeVal.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "输入不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
changeAgeVal.setText("");
}
else if (!changeAgeVal.getText().matches("^\\d+$")) {
JOptionPane.showMessageDialog(null, "输入必须为数字!", "错误", JOptionPane.ERROR_MESSAGE);
changeAgeVal.setText("");
}
else{
System.out.println("ccccccccccccccc"+symbol);
if(symbol=='+'){
age1 = age+Integer.parseInt(changeAgeVal.getText());
System.out.println("ageeeeeeeeeeee++++++"+age1);
if(age1<10||age1>80){
JOptionPane.showMessageDialog(null, "年龄修改失败!修改后年龄应该在[10,80]区间,请重新输入!", "错误", JOptionPane.ERROR_MESSAGE);
changeAgeVal.setText("");
}
else{
dbOper.updateStudent(id,students[1].toString(),age1,students[3].toString());
mainFrame.returnToMain();
dispose();
}
}
else {
age1 = age-Integer.parseInt(changeAgeVal.getText());
System.out.println("ageeeeeeeeeeee----"+age1);
if(age1<10||age1>80){
JOptionPane.showMessageDialog(null, "年龄修改失败!修改后年龄应该在[10,80]区间,请重新输入!", "错误", JOptionPane.ERROR_MESSAGE);
changeAgeVal.setText("");
}
else{
dbOper.updateStudent(id,students[1].toString(),age1,students[3].toString());
mainFrame.returnToMain();
dispose();
}
}
}
}
public void main(String[] args) {
StudentManagementUI mainFrame = new StudentManagementUI();
new changeAgeUI(mainFrame, this.students,this.symbol);
}
}
界面展示
主界面:进入主界面就获取数据库全部学生信息,在主界面的table中逐行展示,在查询键右侧的输入框中输入信息,点击按id查询或按性别查询,进行学生信息的查询。
同样是在该输入框,输入学生id,点击修改按钮,可以修改该学生信息
新增学生功能
修改年龄功能,在表格中选中要修改年龄的学生,点击增加或减少年龄按钮,输入要修改的年龄
在表格中右键删除学生信息
整完了,以后要整的项目可太多了,白白