啥也不懂的我也想为长理学子撑撑伞,基本没有bug,时间问题选课的功能其实可以再完善一点。
制作粗糙但功能基本完善,足以应付课程设计
数据库建表代码我放到最后
先是sqlserve的连接、登录窗口设计以及实现登录和注册功能
ps:这里改成你数据库建立的库名和你自己设定的数据库登录密码!!
private static String DBDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
protected static String DBURL = "jdbc:sqlserver://localhost:1433;DatabaseName=选课系统;trustServerCertificate=true";
protected static String DBUSER = "sa";
protected static String DBPASS = "Dong1225@";
package keshe;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
class LoginFrame extends JFrame implements ActionListener {
private static String DBDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
protected static String DBURL = "jdbc:sqlserver://localhost:1433;DatabaseName=选课系统;trustServerCertificate=true";
protected static String DBUSER = "sa";
protected static String DBPASS = "Dong1225@";
private JLabel a1 = new JLabel("用户名");
private JTextField username = new JTextField();
private JLabel a2 = new JLabel("密 码");
private JPasswordField password = new JPasswordField();
private ButtonGroup group = new ButtonGroup();
private JRadioButton student = new JRadioButton("学生端");
private JRadioButton teacher = new JRadioButton("管理端");
private JButton okbtn = new JButton("登录");
private JButton regbtn = new JButton("注册");
public JButton personalInfoBtn = new JButton("教师个人信息查询");
public JButton courseInfoBtn = new JButton("课程信息发布");
public JButton studentInfoBtn = new JButton("学生信息");
public JButton exitBtn = new JButton("退出系统");
private Connection dbConn;
public LoginFrame() {
try {
Class.forName(DBDRIVER);
System.out.println("加载驱动成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
try {
dbConn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
System.out.println("连接数据库成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.print("SQL Server连接失败!");
}
// 设置窗体的位置及大小
setBounds(600, 200, 300, 220);
// 设置按下右上角X号后关闭
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 初始化--往窗体里放其他控件
setLayout(new BorderLayout());// 布局管理器
// 输入部分
JPanel fieldPanel = new JPanel();
fieldPanel.setLayout(null);
a1.setBounds(50, 20, 50, 20);
a2.setBounds(50, 60, 50, 20);
fieldPanel.add(a1);
fieldPanel.add(a2);
username.setBounds(110, 20, 120, 20);
password.setBounds(110, 60, 120, 20);
fieldPanel.add(username);
fieldPanel.add(password);
// 用户身份选择
student.setBounds(70, 100, 80, 20);
teacher.setBounds(160, 100, 80, 20);
fieldPanel.add(student);
fieldPanel.add(teacher);
group.add(student);
group.add(teacher);
add(fieldPanel, BorderLayout.CENTER);
// 按钮部分
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(okbtn);
buttonPanel.add(regbtn);
add(buttonPanel, BorderLayout.SOUTH);
// 添加事件监听
okbtn.addActionListener(this);
regbtn.addActionListener(this);
//窗体居中
setLocationRelativeTo(null);
// 设置窗体可见
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == regbtn) {
if (student.isSelected()) {
// 学生端注册
String user = username.getText().trim();
String pass = new String(password.getPassword());
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
String query = "INSERT INTO student_users(username, password) VALUES(?, ?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, user);
stmt.setString(2, pass);
stmt.executeUpdate();
JOptionPane.showMessageDialog(this, "学生端注册成功!");
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "学生端注册失败!");
}
} else if (teacher.isSelected()) {
// 教师端注册
String user = username.getText().trim();
String pass = new String(password.getPassword());
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
String query = "INSERT INTO teacher_users(username, password) VALUES(?, ?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, user);
stmt.setString(2, pass);
stmt.executeUpdate();
JOptionPane.showMessageDialog(this, "教师端注册成功!");
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "教师端注册失败!");
}
}
} else if (e.getSource() == okbtn) {
if (student.isSelected()) {
// 学生端登录验证
String user = username.getText().trim();
String pass = new String(password.getPassword());
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
String query = "SELECT * FROM student_users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, user);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
// 登录成功
JOptionPane.showMessageDialog(this, "学生端登录成功!");
} else {
// 登录失败
JOptionPane.showMessageDialog(this, "学生端登录失败!用户名或密码错误!");
username.setText(""); // 清空用户名字段
password.setText(""); // 清空密码字段
return;
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "学生端登录失败!");
dispose(); // 关闭登录窗口
}
StudentFunctionFrame studentFrame = new StudentFunctionFrame(this, dbConn);
dispose(); // 关闭当前窗口
} else if (teacher.isSelected()) {
// 教师端登录验证
String user = username.getText().trim();
String pass = new String(password.getPassword());
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
String query = "SELECT * FROM teacher_users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, user);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
// 登录成功
JOptionPane.showMessageDialog(this, "管理端登录成功!");
} else {
// 登录失败
JOptionPane.showMessageDialog(this, "管理端登录失败!用户名或密码错误!");
username.setText(""); // 清空用户名字段
password.setText(""); // 清空密码字段
return;
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "管理端登录失败!");
}
ManagementFunctionFrame teacherFrame = new ManagementFunctionFrame(this, dbConn);
dispose(); // 关闭登录窗口
}
}
}
}
效果实现
下面这一块是管理端的界面布局以及事件触发
class ManagementFunctionFrame extends JFrame implements ActionListener {
private JButton personalInfoBtn;
private JButton courseInfoBtn;
private JButton studentInfoBtn;
private JButton exitBtn;
private Connection Conn; // 声明数据库连接变量
public ManagementFunctionFrame(LoginFrame loginFrame, Connection conn) {
this.personalInfoBtn = loginFrame.personalInfoBtn;
this.courseInfoBtn = loginFrame.courseInfoBtn;
this.studentInfoBtn = loginFrame.studentInfoBtn;
this.Conn = conn;
createGUI();
}
public void createGUI() {
setTitle("管理端界面");
setSize(580, 670);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
// 个人信息查询按钮
personalInfoBtn = new JButton("教师信息");
personalInfoBtn.setBounds(new Rectangle(230, 100, 120, 60));
panel.add(personalInfoBtn);
// 课程信息发布按钮
courseInfoBtn = new JButton("课程信息发布");
courseInfoBtn.setBounds(new Rectangle(230, 220, 120, 60));
panel.add(courseInfoBtn);
// 学生信息按钮
studentInfoBtn = new JButton("学生信息");
studentInfoBtn.setBounds(new Rectangle(230, 340, 120, 60));
panel.add(studentInfoBtn);
// 退出系统按钮
exitBtn = new JButton("退出系统");
exitBtn.setBounds(new Rectangle(230, 460, 120, 60));
panel.add(exitBtn);
add(panel);
// 添加事件监听
personalInfoBtn.addActionListener(this);
courseInfoBtn.addActionListener(this);
studentInfoBtn.addActionListener(this);
exitBtn.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// 处理按钮点击事件
if (e.getSource() == personalInfoBtn) {
TeacherFrame personalInfoFrame = new TeacherFrame(Conn);
personalInfoFrame.setVisible(true);
setLocationRelativeTo(null);
} else if (e.getSource() == courseInfoBtn) {
// 执行课程信息发布操作
CourseInfoFrame courseInfoFrame = new CourseInfoFrame(Conn);
courseInfoFrame.setVisible(true);
} else if (e.getSource() == studentInfoBtn) {
// 执行学生信息操作
StudentInfoFrame studentInfoFrame = new StudentInfoFrame(Conn);
studentInfoFrame.setVisible(true);
} else if (e.getSource() == exitBtn) {
// 退出系统
System.exit(0);
}
}
}
效果实现:
以下代码是实现教师信息这个模块功能:
class TeacherFrame extends JFrame implements ActionListener {
private JTextField teacherIdField;
private JTextField teacherNameField;
private JTextField teacherPhoneField;
private JTextField teachingNameField;
private JButton addButton;
private JButton deleteButton;
private JButton updateButton;
private JButton queryButton; // 新增查询按钮
private Connection conn;
//文本清除
public void teacher_clear() {
teacherIdField.setText("");
teacherNameField.setText("");
teacherPhoneField.setText("");
teachingNameField.setText("");
}
public TeacherFrame(Connection conn) {
this.conn = conn;
setTitle("教师信息");
setSize(300, 250);
setLocationRelativeTo(null);
setLayout(new GridLayout(6, 2));
JLabel teacherIdLabel = new JLabel("职工号:");
teacherIdField = new JTextField();
JLabel teacherNameLabel = new JLabel("姓名:");
teacherNameField = new JTextField();
JLabel teacherPhoneLabel = new JLabel("电话:");
teacherPhoneField = new JTextField();
JLabel teachingNameLabel = new JLabel("授课课程:");
teachingNameField = new JTextField();
addButton = new JButton("添加");
deleteButton = new JButton("删除");
updateButton = new JButton("修改");
queryButton = new JButton("查询"); // 创建查询按钮
add(teacherIdLabel);
add(teacherIdField);
add(teacherNameLabel);
add(teacherNameField);
add(teacherPhoneLabel);
add(teacherPhoneField);
add(teachingNameLabel);
add(teachingNameField);
add(addButton);
add(deleteButton);
add(updateButton);
add(queryButton); // 添加查询按钮
addButton.addActionListener(this);
deleteButton.addActionListener(this);
updateButton.addActionListener(this);
queryButton.addActionListener(this); // 添加查询按钮的事件监听器
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
// 添加个人信息
String teacherId = teacherIdField.getText();
String teacherName = teacherNameField.getText();
String teacherPhone = teacherPhoneField.getText();
String teachingName = teachingNameField.getText();
try {
// 创建预编译的 SQL 语句
String sql = "INSERT INTO teachers (teacher_id, teacher_name, teacher_phone, teaching_name) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setInt(1, Integer.parseInt(teacherId));
statement.setString(2, teacherName);
statement.setString(3, teacherPhone);
statement.setString(4, teachingName);
// 执行插入操作
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("教师信息添加成功!");
JOptionPane.showMessageDialog(this, "教师信息添加成功!");
teacher_clear();
} else {
System.out.println("教师信息添加失败!");
JOptionPane.showMessageDialog(this, "教师信息添加失败!");
}
// 关闭 statement
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "教师信息添加失败!");
}
} else if (e.getSource() == deleteButton) {
// 删除个人信息
String teacherId = JOptionPane.showInputDialog(this, "请输入要删除的教师职工号:");
if (teacherId != null && !teacherId.isEmpty()) {
try {
// 创建预编译的 SQL 语句
String sql = "DELETE FROM teachers WHERE teacher_id = ?";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setInt(1, Integer.parseInt(teacherId));
// 执行删除操作
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("教师信息删除成功!");
JOptionPane.showMessageDialog(this, "教师信息删除成功!");
teacher_clear();
} else {
System.out.println("未找到该职工号的教师,教师信息删除失败!");
JOptionPane.showMessageDialog(this, "未找到该职工号的教师,教师信息删除失败!");
}
// 关闭 statement
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "教师信息删除失败!");
}
}
} else if (e.getSource() == updateButton) {
// 修改个人信息
// 弹出文本框并让用户选择要修改的教师信息
String teacherId = JOptionPane.showInputDialog(this, "请输入要修改的教师职工号:");
if (teacherId != null && !teacherId.isEmpty()) {
// 根据职工号查询教师信息
try {
String sql = "SELECT * FROM teachers WHERE teacher_id = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, Integer.parseInt(teacherId));
ResultSet resultSet = statement.executeQuery();
// 如果查询到了结果
if (resultSet.next()) {
String currentTeacherName = resultSet.getString("teacher_name");
String currentTeacherPhone = resultSet.getString("teacher_phone");
String currentTeachingName = resultSet.getString("teaching_name");
// 弹出对话框让用户修改教师信息
JTextField nameField = new JTextField(currentTeacherName);
JTextField phoneField = new JTextField(currentTeacherPhone);
JTextField teachingField = new JTextField(currentTeachingName);
Object[] message = {
"姓名:", nameField,
"电话:", phoneField,
"授课课程:", teachingField
};
int option = JOptionPane.showConfirmDialog(this, message, "修改教师信息", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String updatedTeacherName = nameField.getText();
String updatedTeacherPhone = phoneField.getText();
String updatedTeachingName = teachingField.getText();
// 执行更新操作
String updateSql = "UPDATE teachers SET teacher_name = ?, teacher_phone = ?, teaching_name = ? WHERE teacher_id = ?";
PreparedStatement updateStatement = conn.prepareStatement(updateSql);
updateStatement.setString(1, updatedTeacherName);
updateStatement.setString(2, updatedTeacherPhone);
updateStatement.setString(3, updatedTeachingName);
updateStatement.setInt(4, Integer.parseInt(teacherId));
int rowsUpdated = updateStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("教师信息修改成功!");
JOptionPane.showMessageDialog(this, "教师信息修改成功!");
teacher_clear();
} else {
System.out.println("教师信息修改失败!");
JOptionPane.showMessageDialog(this, "教师信息修改失败!");
}
updateStatement.close();
}
} else {
JOptionPane.showMessageDialog(this, "没有找到该教师信息!", "教师信息查询结果", JOptionPane.INFORMATION_MESSAGE);
}
statement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "教师信息查询失败!");
}
}
} else if (e.getSource() == queryButton) {
// 查询个人信息
try {
// 创建查询语句
String sql = "SELECT * FROM teachers";
Statement statement = conn.createStatement();
// 执行查询
ResultSet resultSet = statement.executeQuery(sql);
// 处理查询结果
StringBuilder result = new StringBuilder();
while (resultSet.next()) {
int teacherId = resultSet.getInt("teacher_id");
String teacherName = resultSet.getString("teacher_name");
String teacherPhone = resultSet.getString("teacher_phone");
String teachingName = resultSet.getString("teaching_name");
result.append("------------------------\n");
result.append("职工号: ").append(teacherId).append("\n");
result.append("姓名: ").append(teacherName).append("\n");
result.append("电话: ").append(teacherPhone).append("\n");
result.append("授课课程: ").append(teachingName).append("\n");
result.append("------------------------\n");
}
if (result.length() > 0) {
System.out.println("教师信息查询成功!");
JOptionPane.showMessageDialog(this, result.toString(), "教师信息查询结果", JOptionPane.INFORMATION_MESSAGE);
} else {
System.out.println("教师信息查询失败!");
JOptionPane.showMessageDialog(this, "没有找到教师信息!", "教师信息查询结果", JOptionPane.INFORMATION_MESSAGE);
}
// 关闭 statement 和 resultSet
statement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "教师信息查询失败!");
}
}
}
}
效果展示(四个功能都可以实现,为了方便我只展示查询):
然后是课程信息发布模块:
class CourseInfoFrame extends JFrame implements ActionListener {
private JTextField subjectNameField;
private JTextField classTimeField;
private JTextField classLocationField;
private JTextField teacherNameField;
private JButton addButton;
private JButton deleteButton;
private JButton updateButton;
private JButton searchButton;
private Connection conn;
public void student_clear() {
subjectNameField.setText("");
classTimeField.setText("");
classLocationField.setText("");
teacherNameField.setText("");
}
public CourseInfoFrame(Connection conn) {
this.conn = conn;
setTitle("课程信息发布");
setSize(300, 250);
setLocationRelativeTo(null);
setLayout(new GridLayout(6, 2));
// 创建标签和文本框
JLabel subjectNameLabel = new JLabel("课程名称:");
subjectNameField = new JTextField();
JLabel classTimeLabel = new JLabel("上课时间:");
classTimeField = new JTextField();
JLabel classLocationLabel = new JLabel("上课地点:");
classLocationField = new JTextField();
JLabel teacherNameLabel = new JLabel("老师姓名:");
teacherNameField = new JTextField();
// 创建按钮
addButton = new JButton("添加");
deleteButton = new JButton("删除");
updateButton = new JButton("修改");
searchButton = new JButton("查找");
// 将标签、文本框和按钮添加到窗口中
add(subjectNameLabel);
add(subjectNameField);
add(classTimeLabel);
add(classTimeField);
add(classLocationLabel);
add(classLocationField);
add(teacherNameLabel);
add(teacherNameField);
add(addButton);
add(deleteButton);
add(updateButton);
add(searchButton);
// 注册按钮的点击事件监听器
addButton.addActionListener(this);
deleteButton.addActionListener(this);
updateButton.addActionListener(this);
searchButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
// 执行添加课程操作
String subjectName = subjectNameField.getText();
String classTime = classTimeField.getText();
String classLocation = classLocationField.getText();
String teacherName = teacherNameField.getText();
try {
// 创建预编译的 SQL 语句
String sql = "INSERT INTO subjects ( subject_name, class_time, class_location, teacher_name) VALUES ( ?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setString(1, subjectName);
statement.setString(2, classTime);
statement.setString(3, classLocation);
statement.setString(4, teacherName);
// 执行插入操作
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("课程信息添加成功!");
JOptionPane.showMessageDialog(this, "课程信息添加成功!");
student_clear();
} else {
System.out.println("课程信息添加失败!");
JOptionPane.showMessageDialog(this, "课程信息添加失败!");
student_clear();
}
// 关闭 statement
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "课程信息添加失败!");
}
} else if (e.getSource() == deleteButton) {
String subjectName = JOptionPane.showInputDialog(this, "请输入要删除的课程名称:");
if (subjectName != null && !subjectName.isEmpty()) {
try {
// 创建预编译的 SQL 语句
String sql = "DELETE FROM subjects WHERE subject_name = ?";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setString(1, subjectName);
// 执行删除操作
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("课程信息删除成功!");
JOptionPane.showMessageDialog(this, "课程信息删除成功!");
student_clear();
} else {
System.out.println("未找到该课程,课程信息删除失败!");
JOptionPane.showMessageDialog(this, "未找到该课程,课程信息删除失败!");
student_clear();
}
// 关闭 statement
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "课程信息删除失败!");
}
}
} else if (e.getSource() == updateButton) {
// 执行修改课程操作
String subjectName1 = JOptionPane.showInputDialog(this, "请输入要修改的课程名字:");
if (subjectName1 != null && !subjectName1.isEmpty()) {
try {
// 创建预编译的 SQL 语句
String sql = "SELECT * FROM subjects WHERE subject_name = ?";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setString(1, subjectName1);
// 执行查询
ResultSet resultSet = statement.executeQuery();
// 处理查询结果
if (resultSet.next()) {
// 获取课程信息
String subjectName = resultSet.getString("subject_name");
String classTime = resultSet.getString("class_time");
String classLocation = resultSet.getString("class_location");
String teacherName = resultSet.getString("teacher_name");
// 编辑课程信息
JTextField subjectNameField = new JTextField(subjectName);
JTextField classTimeField = new JTextField(classTime);
JTextField classLocationField = new JTextField(classLocation);
JTextField teacherNameField = new JTextField(teacherName);
Object[] message = {
"课程名称:", subjectNameField,
"上课时间:", classTimeField,
"上课地点:", classLocationField,
"老师姓名:", teacherNameField
};
int option = JOptionPane.showConfirmDialog(this, message, "修改课程信息", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
// 更新课程信息
String updateSql = "UPDATE subjects SET class_time = ?, class_location = ?, teacher_name = ? WHERE subject_name = ?";
PreparedStatement updateStatement = conn.prepareStatement(updateSql);
updateStatement.setString(1, classTimeField.getText());
updateStatement.setString(2, classLocationField.getText());
updateStatement.setString(3, teacherNameField.getText());
updateStatement.setString(4, subjectName1);
// 执行更新操作
int rowsUpdated = updateStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("课程信息更新成功!");
JOptionPane.showMessageDialog(this, "课程信息更新成功!");
student_clear();
} else {
System.out.println("课程信息更新失败!");
JOptionPane.showMessageDialog(this, "课程信息更新失败!");
}
// 关闭更新的 statement
updateStatement.close();
}
} else {
JOptionPane.showMessageDialog(this, "找不到该课程信息!", "课程信息查询结果", JOptionPane.INFORMATION_MESSAGE);
}
// 关闭查询的 statement 和 resultSet
statement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "课程信息查询失败!");
}
}
} else if (e.getSource() == searchButton) {
// 执行查询课程信息操作
try {
// 创建查询语句
String sql = "SELECT * FROM subjects";
Statement statement = conn.createStatement();
// 执行查询
ResultSet resultSet = statement.executeQuery(sql);
// 处理查询结果
StringBuilder result = new StringBuilder();
result.append("课程信息查询结果:\n\n");
while (resultSet.next()) {
String subjectName = resultSet.getString("subject_name");
String classTime = resultSet.getString("class_time");
String classLocation = resultSet.getString("class_location");
String teacherName = resultSet.getString("teacher_name");
result.append("------------------------\n");
result.append("课程名称: ").append(subjectName).append("\n");
result.append("上课时间: ").append(classTime).append("\n");
result.append("上课地点: ").append(classLocation).append("\n");
result.append("老师姓名: ").append(teacherName).append("\n");
result.append("------------------------\n");
}
if (result.length() > 0) {
System.out.println(result.toString());
JOptionPane.showMessageDialog(this, result.toString(), "课程信息查询结果", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "找不到符合条件的课程信息!", "课程信息查询结果", JOptionPane.INFORMATION_MESSAGE);
}
// 关闭 statement 和 resultSet
statement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "课程信息查询失败!");
}
}
}
}
效果(只展示修改功能):
最后是管理端的学生信息模块:
class StudentInfoFrame extends JFrame implements ActionListener {
private JTextField studentIdField;
private JTextField studentNameField;
private JTextField studentNumberField;
private JTextField classNameField;
private JButton addButton;
private JButton deleteButton;
private JButton updateButton;
private JButton queryButton;
private Connection conn;
public void student_clear() {
studentIdField.setText("");
studentNameField.setText("");
studentNumberField.setText("");
classNameField.setText("");
}
public StudentInfoFrame(Connection conn) {
this.conn = conn;
setTitle("学生信息");
setSize(300, 250);
setLocationRelativeTo(null);
setLayout(new GridLayout(6, 2));
JLabel studentIdLabel = new JLabel("学生学号:");
studentIdField = new JTextField();
JLabel studentNameLabel = new JLabel("学生姓名:");
studentNameField = new JTextField();
JLabel studentNumberLabel = new JLabel("学生班级:");
studentNumberField = new JTextField();
JLabel classNameLabel = new JLabel("学生选课信息:");
classNameField = new JTextField();
addButton = new JButton("添加");
deleteButton = new JButton("删除");
updateButton = new JButton("修改");
queryButton = new JButton("查询");
add(studentIdLabel);
add(studentIdField);
add(studentNameLabel);
add(studentNameField);
add(studentNumberLabel);
add(studentNumberField);
add(classNameLabel);
add(classNameField);
add(addButton);
add(deleteButton);
add(updateButton);
add(queryButton);
addButton.addActionListener(this);
deleteButton.addActionListener(this);
updateButton.addActionListener(this);
queryButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
// 执行添加学生操作
String studentId = studentIdField.getText();
String studentName = studentNameField.getText();
String studentNumber = studentNumberField.getText();
String className = classNameField.getText();
try {
// 创建预编译的 SQL 语句
String sql = "INSERT INTO students (student_id, student_name, student_number, class_name) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setInt(1, Integer.parseInt(studentId));
statement.setString(2, studentName);
statement.setString(3, studentNumber);
statement.setString(4, className);
// 执行插入操作
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("学生信息添加成功!");
JOptionPane.showMessageDialog(this, "学生信息添加成功!");
student_clear();
} else {
System.out.println("学生信息添加失败!");
JOptionPane.showMessageDialog(this, "学生信息添加失败!");
}
// 关闭 statement
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "学生信息添加失败!");
}
} else if (e.getSource() == deleteButton) {
// 执行删除学生操作
String studentId = JOptionPane.showInputDialog(this, "请输入要删除的学生学号:");
if (studentId != null && !studentId.isEmpty()) {
try {
// 创建预编译的 SQL 语句
String sql = "DELETE FROM students WHERE student_id = ?";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setInt(1, Integer.parseInt(studentId));
// 执行删除操作
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("学生信息删除成功!");
JOptionPane.showMessageDialog(this, "学生信息删除成功!");
student_clear();
} else {
System.out.println("未找到该学号的学生,学生信息删除失败!");
JOptionPane.showMessageDialog(this, "学生信息删除失败!");
}
// 关闭 statement
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "学生信息删除失败!");
}
}
} else if (e.getSource() == updateButton) {
/// 执行修改学生操作
String studentId = JOptionPane.showInputDialog(this, "请输入要修改的学生学号:");
if (studentId != null && !studentId.isEmpty()) {
try {
// 创建预编译的 SQL 语句
String sql = "SELECT * FROM students WHERE student_id = ?";
PreparedStatement statement = conn.prepareStatement(sql);
// 设置参数值
statement.setInt(1, Integer.parseInt(studentId));
// 执行查询
ResultSet resultSet = statement.executeQuery();
// 处理查询结果
if (resultSet.next()) {
// 获取学生信息
String studentName = resultSet.getString("student_name");
String studentNumber = resultSet.getString("student_number");
String className = resultSet.getString("class_name");
//编辑学生信息
JTextField studentNameField = new JTextField(studentName);
JTextField studentNumberField = new JTextField(studentNumber);
JTextField classNameField = new JTextField(className);
Object[] message = {
"学生姓名:", studentNameField,
"学生班级:", studentNumberField,
"学生选课信息:", classNameField
};
int option = JOptionPane.showConfirmDialog(this, message, "修改学生信息", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
// 更新学生信息
String updateSql = "UPDATE students SET student_name = ?, student_number = ?, class_name = ? WHERE student_id = ?";
PreparedStatement updateStatement = conn.prepareStatement(updateSql);
updateStatement.setString(1, studentNameField.getText());
updateStatement.setString(2, studentNumberField.getText());
updateStatement.setString(3, classNameField.getText());
updateStatement.setInt(4, Integer.parseInt(studentId));
// 执行更新操作
int rowsUpdated = updateStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("学生信息更新成功!");
JOptionPane.showMessageDialog(this, "学生信息更新成功!");
student_clear();
} else {
System.out.println("学生信息更新失败!");
JOptionPane.showMessageDialog(this, "学生信息更新失败!");
}
// 关闭更新的 statement
updateStatement.close();
}
} else {
JOptionPane.showMessageDialog(this, "找不到指定学号的学生信息!", "学生信息查询结果", JOptionPane.INFORMATION_MESSAGE);
}
// 关闭查询的 statement 和 resultSet
statement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "学生信息查询失败!");
}
}
}
else if (e.getSource() == queryButton) {
// 查询个人信息
try {
// 创建查询语句
String sql = "SELECT * FROM students";
Statement statement = conn.createStatement();
// 执行查询
ResultSet resultSet = statement.executeQuery(sql);
// 处理查询结果
StringBuilder result = new StringBuilder();
while (resultSet.next()) {
int studentId = resultSet.getInt("student_id");
String studentName = resultSet.getString("student_name");
String studentNumber = resultSet.getString("student_number");
String className = resultSet.getString("class_name");
result.append("------------------------\n");
result.append("学生学号: ").append(studentId).append("\n");
result.append("学生姓名: ").append(studentName).append("\n");
result.append("学生班级: ").append(studentNumber).append("\n");
result.append("学生选课信息: ").append(className).append("\n");
result.append("------------------------\n");
}
if (result.length() > 0) {
System.out.println("学生信息查询成功!");
JOptionPane.showMessageDialog(this, result.toString(), "学生信息查询结果", JOptionPane.INFORMATION_MESSAGE);
} else {
System.out.println("学生信息查询失败!");
JOptionPane.showMessageDialog(this, "没有找到学生信息!", "学生信息查询结果", JOptionPane.INFORMATION_MESSAGE);
}
// 关闭 statement 和 resultSet
statement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "学生信息查询失败!");
}
}
}
}
效果:
----------------------------------------------接下来就是学生端设计-----------------------------------------------------
学生端界面布局:
class StudentFunctionFrame extends JFrame implements ActionListener {
private JButton courseInfoBtn;
private JButton personalInfoBtn;
private JButton exitBtn;
private Connection conn;
private String selectedCourse;
public StudentFunctionFrame(LoginFrame loginFrame, Connection conn) {
this.courseInfoBtn = loginFrame.courseInfoBtn;
this.personalInfoBtn = loginFrame.personalInfoBtn;
this.exitBtn = loginFrame.exitBtn;
this.conn = conn;
createGUI();
}
private void createGUI() {
setTitle("学生端界面");
setSize(640, 620);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
// 课程信息按钮
courseInfoBtn = new JButton("课程信息");
courseInfoBtn.setBounds(new Rectangle(250, 100, 140, 60));
panel.add(courseInfoBtn);
// 个人信息按钮
personalInfoBtn = new JButton("个人信息");
personalInfoBtn.setBounds(new Rectangle(250, 250, 140, 60));
panel.add(personalInfoBtn);
// 退出系统按钮
exitBtn = new JButton("退出系统");
exitBtn.setBounds(new Rectangle(250, 400, 140, 60));
panel.add(exitBtn);
add(panel);
// 添加事件监听
courseInfoBtn.addActionListener(this);
personalInfoBtn.addActionListener(this);
exitBtn.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == courseInfoBtn) {
// 执行课程信息操作
CourseselectionFrame courseselectionFrame = new CourseselectionFrame(conn, this);
courseselectionFrame.setVisible(true);
} else if (e.getSource() == personalInfoBtn) {
// 执行个人信息操作
String studentNumber = JOptionPane.showInputDialog(null, "请输入学号:");
if (studentNumber != null && !studentNumber.isEmpty()) {
StudentPersonalInformation studentPersonalInformation = new StudentPersonalInformation(conn, studentNumber, selectedCourse);
studentPersonalInformation.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "请输入有效的学号");
}
} else if (e.getSource() == exitBtn) {
// 退出系统
System.exit(0);
}
}
public void setSelectedCourse(String course) {
selectedCourse = course;
}
}
然后就是选课功能实现:
class CourseselectionFrame extends JFrame {
private JButton selectBtn;
private JTable courseTable;
private Connection conn;
private StudentFunctionFrame studentFunctionFrame;
public CourseselectionFrame(Connection conn, StudentFunctionFrame studentFunctionFrame) {
this.conn = conn;
this.studentFunctionFrame = studentFunctionFrame;
createGUI();
}
private void createGUI() {
setTitle("课程信息");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
// 创建课程表格
courseTable = new JTable();
panel.add(new JScrollPane(courseTable), BorderLayout.CENTER);
// 添加选择按钮
selectBtn = new JButton("选择");
panel.add(selectBtn, BorderLayout.SOUTH);
add(panel);
// 添加事件监听
selectBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = courseTable.getSelectedRow();
if (selectedRow != -1) {
String subjectName = (String) courseTable.getValueAt(selectedRow, 0);
String classTime = (String) courseTable.getValueAt(selectedRow, 1);
String classLocation = (String) courseTable.getValueAt(selectedRow, 2);
String teacherName = (String) courseTable.getValueAt(selectedRow, 3);
// 弹出输入学号的对话框
String studentId = JOptionPane.showInputDialog(null, "请输入学号:");
if (studentId != null && !studentId.isEmpty()) {
// 执行选课操作
boolean success = selectCourse(subjectName, studentId);
if (success) {
JOptionPane.showMessageDialog(null, "选课成功!");
studentFunctionFrame.setSelectedCourse(subjectName);
} else {
JOptionPane.showMessageDialog(null, "选课失败,请检查学号是否有效");
}
} else {
JOptionPane.showMessageDialog(null, "请输入有效的学号");
}
} else {
JOptionPane.showMessageDialog(null, "请选择一门课程");
}
}
});
setVisible(true);
// 加载课程信息
loadCourseInfo();
}
private void loadCourseInfo() {
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT subject_name, class_time, class_location, teacher_name FROM subjects");
// 创建表格模型
DefaultTableModel model = new DefaultTableModel(new String[]{"课程名称", "上课时间", "上课地点", "教师姓名"}, 0);
// 将查询结果添加到表格模型中
while (rs.next()) {
String subjectName = rs.getString("subject_name");
String classTime = rs.getString("class_time");
String classLocation = rs.getString("class_location");
String teacherName = rs.getString("teacher_name");
model.addRow(new Object[]{subjectName, classTime, classLocation, teacherName});
}
// 设置表格模型
courseTable.setModel(model);
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private boolean selectCourse(String subjectName, String studentId) {
try {
Statement stmt = conn.createStatement();
// 检查学生是否存在
ResultSet studentResult = stmt.executeQuery("SELECT student_id FROM students WHERE student_id = '" + studentId + "'");
if (!studentResult.next()) {
return false;
}
// 检查课程是否存在
ResultSet courseResult = stmt.executeQuery("SELECT subject_name FROM subjects WHERE subject_name = '" + subjectName + "'");
if (!courseResult.next()) {
return false;
}
// 检查学生是否已选择该课程
ResultSet selectionResult = stmt.executeQuery("SELECT class_name FROM students WHERE student_id = '" + studentId + "' AND class_name = '" + subjectName + "'");
if (selectionResult.next()) {
return false;
}
// 执行选课操作
int rowsAffected = stmt.executeUpdate("UPDATE students SET class_name = '" + subjectName + "' WHERE student_id = '" + studentId + "'");
stmt.close();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
最后是个人信息的查询:
class StudentPersonalInformation extends JFrame {
private Connection conn;
private String studentNumber;
private String selectedCourse;
private JTextField studentNumberField;
private JButton searchButton;
private JLabel studentIdLabel;
private JLabel studentNameLabel;
private JLabel classNameLabel;
private JButton modifyButton;
public StudentPersonalInformation(Connection conn, String studentNumber, String selectedCourse) {
this.conn = conn;
this.studentNumber = studentNumber;
this.selectedCourse = selectedCourse;
createGUI();
}
private void createGUI() {
setTitle("学生信息");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(5, 5, 5, 5);
// 学号
JLabel studentNumberTextLabel = new JLabel("学号:");
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(studentNumberTextLabel, constraints);
studentNumberField = new JTextField(20);
studentNumberField.setText(studentNumber);
studentNumberField.setEditable(false);
constraints.gridx = 1;
panel.add(studentNumberField, constraints);
// 学号
JLabel studentIdTextLabel = new JLabel("姓名:");
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(studentIdTextLabel, constraints);
studentIdLabel = new JLabel();
constraints.gridx = 1;
panel.add(studentIdLabel, constraints);
// 姓名
JLabel studentNameTextLabel = new JLabel("班级:");
constraints.gridx = 0;
constraints.gridy = 2;
panel.add(studentNameTextLabel, constraints);
studentNameLabel = new JLabel();
constraints.gridx = 1;
panel.add(studentNameLabel, constraints);
// 班级
JLabel classNameTextLabel = new JLabel("所选的课程:");
constraints.gridx = 0;
constraints.gridy = 3;
panel.add(classNameTextLabel, constraints);
classNameLabel = new JLabel();
constraints.gridx = 1;
panel.add(classNameLabel, constraints);
// 修改按钮
modifyButton = new JButton("退选");
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 5;
constraints.anchor = GridBagConstraints.CENTER;
panel.add(modifyButton, constraints);
add(panel);
modifyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedClassName = JOptionPane.showInputDialog(null, "请输入要退选的课程名称:");
if (selectedClassName != null && !selectedClassName.isEmpty()) {
modifyClassSelection(selectedClassName);
} else {
JOptionPane.showMessageDialog(null, "请输入有效的课程名称");
}
}
});
setVisible(true);
// Load student information
loadStudentInfo(studentNumber);
}
private void loadStudentInfo(String studentNumber) {
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT student_number, student_name, class_name FROM students WHERE student_id = '" + studentNumber + "'");
if (rs.next()) {
String studentId = rs.getString("student_number");
String studentName = rs.getString("student_name");
String className = rs.getString("class_name");
studentIdLabel.setText(studentId);
studentNameLabel.setText(studentName);
classNameLabel.setText(className);
} else {
JOptionPane.showMessageDialog(null, "未找到该学号对应的学生信息");
clearStudentInfo();
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void modifyClassSelection(String className) {
try {
Statement stmt = conn.createStatement();
String query = "UPDATE students SET class_name = NULL WHERE student_id = '" + studentNumber + "' AND class_name = '" + className + "'";
int rowsAffected = stmt.executeUpdate(query);
if (rowsAffected > 0) {
JOptionPane.showMessageDialog(null, "成功退选课程:" + className);
classNameLabel.setText("");
if (selectedCourse.equals(className)) {
selectedCourse = null;
}
} else {
JOptionPane.showMessageDialog(null, "退选课程失败,请检查输入的课程名称是否正确");
}
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void clearStudentInfo() {
studentIdLabel.setText("");
studentNameLabel.setText("");
classNameLabel.setText("");
}
}
主函数:
package keshe;
public class app {
public static void main(String[] args) {
System.setProperty("sun.java2d.noddraw", "true");//我电脑输入有白框bug才加这一句
new LoginFrame();
}
}
建表,我已经忘记数据库的很多内容了,粗糙的建的库,很多约束没弄,你们可以自己完善一下
CREATE TABLE teachers (
teacher_id INT PRIMARY KEY,
teacher_name VARCHAR(50),
teacher_phone VARCHAR(15),
subject_name VARCHAR(50)
);
CREATE TABLE subjects (
subject_name VARCHAR(50) PRIMARY KEY,
class_time VARCHAR(50),
class_location VARCHAR(50),
teacher_name VARCHAR(50)
);
CREATE TABLE students (
student_id INT PRIMARY KEY,
student_name VARCHAR(50),
student_number VARCHAR(15),
subject_name VARCHAR(50)
);
CREATE TABLE student_users (
username VARCHAR(50) PRIMARY KEY,
password VARCHAR(50)
);
CREATE TABLE teacher_users (
username VARCHAR(50) PRIMARY KEY,
password VARCHAR(50)
);
好了,要去预习了,还有三门课是从零基础开始orz