一、前言
本文展示的代码均为博主大二下学期java实践作业的产物,初学java有很多不足,大家在使用过程中发现可以改进的地方欢迎私信与我讨论。
二、开发环境
java:java 17.0.6
编译器:idealC(版本:2023.1)
数据库:mysql 5.6.23
数据库管理工具:Navicat Premium 17.0.7(有14天的免费试用期,超过期限了需要交费,当时用这个工具是因为它的页面相对简洁,以中文为主,大家在实际应用中不想要付费软件的话也可以用官方的mysql workbench)
外部库:mysql-connector-java-8.0.26.jar(要实现java与数据库连接需要先导入外部库)
以上这些东西的下载安装,大家可以根据自己的需求去找相应的教程,这里就不再赘述了,接下来进入正题~
三、数据准备
(一)导入外部库
为了实现与数据库连接,需要先导入mysql-connector。
①首先下载mysql-connector的jar文件到本地(下载路径没有特别要求,可自定义,用的时候自己能找到就行);
②下载完成后,打开idealC进入自己的项目,点击“文件—>项目结构”
③接着会出现如下界面,在“项目设计”这一列选择“库”这一行,点击“+”在下拉列表中选择“java”,然后选择mysql-connector的jar包的路径添加之后再保存即可
(二)数据库信息准备
打开Navicat,建一个student数据库,里面建两个表,分别是user表和student_info表,前者用来储存管理员登录账号和密码,后者用来储存学生信息(因课程实践时间较短,主要是为了实现系统的功能,所以两个表的设计和输入的内容都比较简单,大家按自身需求自行调整)。
以上就是前期数据准备了,接下来进入正题!
四、登录功能
(一)用户登录
1)登录界面
2)登录界面代码
编写代码规定登录窗口的基础排版样式,设置监听器监控按钮操作,设定if...else语句检验输入内容,弹出相关提示。
package studentsql;import java.awt.*;import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.sql.*;class LoginDialog1 extends JDialog implements ActionListener { private JTextField usernameField; private JPasswordField passwordField; private JButton loginButton; private JLabel messageLabel; public LoginDialog1(JFrame parent) { super(parent, "登录", true); setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.HORIZONTAL; gc.insets = new Insets(5, 5, 5, 5); gc.gridx = 0; gc.gridy = 0; add(new JLabel("用户名:"), gc); gc.gridx = 1; gc.gridy = 0; usernameField = new JTextField(20); add(usernameField, gc); gc.gridx = 0; gc.gridy = 1; add(new JLabel("密码:"), gc); gc.gridx = 1; gc.gridy = 1; passwordField = new JPasswordField(20); add(passwordField, gc); gc.gridx = 1; gc.gridy = 2; loginButton = new JButton("登录"); loginButton.addActionListener(this); add(loginButton, gc); gc.gridx = 1; gc.gridy = 3; messageLabel = new JLabel(""); messageLabel.setForeground(Color.RED); add(messageLabel, gc); pack(); setLocationRelativeTo(parent); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == loginButton) { String username = usernameField.getText(); String password = new String(passwordField.getPassword()); if (isValidLogin(username, password)) { // 登录成功,关闭登录对话框并继续到主界面操作 dispose(); } else { messageLabel.setText("用户名或密码错误,请重试。"); } } }
(二)登录信息验证
1)输入错误信息提示
2)登录成功后显示主界面
3)验证登录信息的代码
// 验证登录信息 private boolean isValidLogin(String username, String password) { try { Class.forName("com.mysql.cj.jdbc.Driver"); String uri = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=gbk";//localhost:3306,其中3306是我的数据库接口,下载时mysql的默认接口是3306,但是如果这个接口被其他软件占用的话,会改成另一个接口号,大家根据自身实际修改接口号;“student?"中的student是我新建的数据库名,大家也按需修改。 Connection conn = DriverManager.getConnection(uri, "填用户名", "填数据库密码");//这里两个双引号内容大家也按需填写 String sql = "SELECT * FROM user WHERE `user_id`=? AND `key`=?"; // 移除列名周围的单引号 PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, username); pstmt.setString(2, password); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { // 仅检查是否有结果 return true; } } catch (Exception ex) { System.err.println("登录验证出错:" + ex.getMessage()); } return false; }}
五、学生信息管理系统主界面
1)功能界面
2)功能界面代码
public class jiemian extends JFrame implements ActionListener { private Connection conn = null; private Statement stmt; private ResultSet rs; private String uri = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=gbk";//有关localhost和student的说明同上一板块代码 private String user = "用户名"; private String password = "填自己的数据库密码"; private JTextField idField, nameField, sexField, specializedField, birthdayField; private JButton addButton, deleteButton, updateButton, queryButton; private JTextArea textArea = new JTextArea(10, 30); public jiemian() { // 初始化组件 initializeComponents(); // 设置窗体基本属性 setTitle("学生管理系统"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void initializeComponents() { // 初始化按钮并添加事件监听器 JPanel buttonPanel = new JPanel(new FlowLayout()); addButton = new JButton("添加"); deleteButton = new JButton("删除"); updateButton = new JButton("修改"); queryButton = new JButton("查询"); buttonPanel.add(addButton); buttonPanel.add(deleteButton); buttonPanel.add(updateButton); buttonPanel.add(queryButton); // 添加按钮事件监听器 addButton.addActionListener(this); deleteButton.addActionListener(this); updateButton.addActionListener(this); queryButton.addActionListener(this); getContentPane().add(buttonPanel, "South"); setLocationRelativeTo(null); setVisible(true); LoginDialog1 loginDialog = new LoginDialog1(this); loginDialog.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == queryButton) { showquery(); } else if (e.getSource() == addButton) { showInsertStudentDialog(); } else if (e.getSource() == deleteButton) { showDeleteStudent(); } else if (e.getSource() == updateButton) { showupdateStudent(); } }
六、查询功能
(一)查询功能操作界面
1)功能操作界面
单击选择查询功能后,跳转到功能操作界面:
2)执行全部查询
3)执行单个查询
4)在单个查询功能中输入不存在学号
5)查询功能代码
private void showquery() { final JDialog dialog = new JDialog(this, "查询学生", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 查询结果区域 JTextArea queryResultArea = new JTextArea(10, 30); queryResultArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(queryResultArea); dialog.getContentPane().add(scrollPane, BorderLayout.CENTER); // 输入面板,用于存放查询条件输入组件 JPanel inputPanel = new JPanel(new FlowLayout()); JTextField studentIdField = new JTextField(20); studentIdField.setVisible(false); inputPanel.add(studentIdField); dialog.getContentPane().add(inputPanel, BorderLayout.NORTH); // 按钮面板,包含全部查询、单个查询和取消按钮 JPanel buttonPanel = new JPanel(); JButton allQueryButton = new JButton("全部查询"); JButton singleQueryButton = new JButton("单个查询"); JButton cancelButton = new JButton("取消"); allQueryButton.addActionListener(e -> { query("全部查询", "", queryResultArea); queryResultArea.setText(textArea.getText()); }); singleQueryButton.addActionListener(e -> { studentIdField.setVisible(true); dialog.revalidate(); // 重新验证对话框布局 dialog.repaint(); // 重绘对话框 }); cancelButton.addActionListener(e -> dialog.dispose()); buttonPanel.add(allQueryButton); buttonPanel.add(singleQueryButton); buttonPanel.add(cancelButton); dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); // 单个查询 JButton confirmQueryButton = new JButton("确认查询"); confirmQueryButton.addActionListener(e -> { String studentId = studentIdField.getText(); if (!studentId.trim().isEmpty()) { query("单个查询", studentId, queryResultArea); queryResultArea.setText(textArea.getText()); } else { JOptionPane.showMessageDialog(dialog, "请输入学生ID", "提示", JOptionPane.WARNING_MESSAGE); } }); // 动态添加确认查询按钮到输入面板,当单个查询被点击时 singleQueryButton.addActionListener(e -> { inputPanel.add(confirmQueryButton); dialog.revalidate(); dialog.repaint(); }); dialog.setVisible(true); } private void query(String queryType, String studentId,JTextArea queryResultArea) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("数据库驱动加载成功"); conn = DriverManager.getConnection(uri, user, password); String queryStr; PreparedStatement pstmt = null; // 初始化PreparedStatement变量 if ("全部查询".equals(queryType)) { queryStr = "SELECT * FROM student_info"; stmt = conn.createStatement(); } else if ("单个查询".equals(queryType) && !studentId.isEmpty()) { queryStr = "SELECT * FROM student_info WHERE id = ?"; pstmt = conn.prepareStatement(queryStr); // 使用PreparedStatement pstmt.setString(1, studentId); } else { textArea.setText("请选择有效的查询类型或输入学生ID"); return; } ResultSet rs; if (pstmt != null) { // 对于单个查询,使用PreparedStatement执行查询 rs = pstmt.executeQuery(); } else { // 全部查询,使用Statement执行 rs = stmt.executeQuery(queryStr); } StringBuilder sb = new StringBuilder(); boolean hasData = false; while (rs.next()) { hasData = true; String stu_id = rs.getString("id"); String stu_sex = rs.getString("sex"); String stu_name = rs.getString("name"); String stu_specialized = rs.getString("specialized"); String stu_birthday = rs.getString("birthday"); sb.append(stu_id).append("\t").append(stu_sex).append("\t") .append(stu_name).append("\t").append(stu_specialized) .append("\t").append(stu_birthday).append("\n"); } if (hasData) { textArea.setText(sb.toString()); } else if ("单个查询".equals(queryType)) { textArea.setText("未找到该学生ID的记录"); } // 确保PreparedStatement关闭 if (pstmt != null) { pstmt.close(); } stmt.close(); // 如果是全部查询,关闭Statement conn.close(); } catch (SQLException ex) { textArea.setText("查询出错:" + ex.getMessage()); } catch (Exception ex) { textArea.setText("系统错误:" + ex.getMessage()); } }
七、添加功能
(一)添加学生
1)添加功能界面
2)添加功能代码
// 添加学生 private void showInsertStudentDialog() { JDialog dialog = new JDialog(this, "添加学生", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 创建输入面板并设置布局 JPanel inputPanel = new JPanel(new GridLayout(10, 10)); inputPanel.add(new JLabel("学号:")); idField = new JTextField(); inputPanel.add(idField); inputPanel.add(new JLabel("姓名:")); nameField = new JTextField(); inputPanel.add(nameField); inputPanel.add(new JLabel("性别:")); sexField = new JTextField(); inputPanel.add(sexField); inputPanel.add(new JLabel("专业:")); specializedField = new JTextField(); inputPanel.add(specializedField); inputPanel.add(new JLabel("生日:")); birthdayField = new JTextField(); inputPanel.add(birthdayField); // 添加输入面板到对话框的中心区域 dialog.getContentPane().add(inputPanel, BorderLayout.CENTER); // 创建按钮面板用于确认和取消按钮 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton confirmButton = new JButton("确认添加"); confirmButton.addActionListener(e -> { // 获取输入值,调用insert方法 insert(); dialog.dispose(); // 关闭对话框 }); buttonPanel.add(confirmButton); JButton cancelButton = new JButton("取消"); cancelButton.addActionListener(e -> dialog.dispose()); // 点击取消时关闭对话框 buttonPanel.add(cancelButton); // 将按钮面板添加到对话框的南侧 dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); dialog.setVisible(true); } private void insert() { String id = idField.getText(); String name = nameField.getText(); String sex = sexField.getText(); String specialized = specializedField.getText(); String birthday = birthdayField.getText(); try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(uri, user, password); String sqlStr = "INSERT INTO student_info(id, sex, name, specialized, birthday) VALUES (?, ?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sqlStr); pstmt.setString(1, id); pstmt.setString(2, sex); pstmt.setString(3, name); pstmt.setString(4, specialized); pstmt.setString(5, birthday); pstmt.executeUpdate(); textArea.append("学生信息添加成功。\n"); } catch (SQLException | ClassNotFoundException ex) { textArea.setText("添加出错:" + ex.getMessage()); } finally { try { if (conn != null) conn.close(); } catch (SQLException ex) { textArea.append("关闭连接出错:" + ex.getMessage()); } } clearInputFields(); // 清空输入框 }
八、删除功能
(一)删除学生
1)删除界面
2)输入不存在的学号
3)执行删除操作
4)删除功能代码
private void showDeleteStudent() { JDialog dialog = new JDialog(this, "删除学生", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 创建一个标签和文本框用于输入学号 JLabel idLabel = new JLabel("请输入要删除学生的学号:"); JTextField idTextField = new JTextField(20); JPanel inputPanel = new JPanel(new FlowLayout()); inputPanel.add(idLabel); inputPanel.add(idTextField); dialog.getContentPane().add(inputPanel, BorderLayout.NORTH); // 创建一个标签用于显示操作结果 JLabel resultLabel = new JLabel("", SwingConstants.CENTER); dialog.getContentPane().add(resultLabel, BorderLayout.CENTER); // 添加确认删除按钮 JButton deleteButton = new JButton("确认删除"); deleteButton.addActionListener(e -> { // 获取输入的学号 String studentId = idTextField.getText(); if (!studentId.isEmpty()) { // 执行删除操作,并传入学号参数 boolean deleted = deleteStudent(studentId); if (deleted) { resultLabel.setText("学生信息删除成功。"); } else { resultLabel.setText("删除失败,未找到匹配的学号。"); } } else { JOptionPane.showMessageDialog(dialog, "请输入学号", "提示", JOptionPane.INFORMATION_MESSAGE); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(deleteButton); dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); dialog.setVisible(true); } private boolean deleteStudent(String studentId) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("数据库驱动加载成功"); conn = DriverManager.getConnection(uri, user, password); String sqlStr = "DELETE FROM student_info WHERE id=?"; PreparedStatement pstmt = conn.prepareStatement(sqlStr); pstmt.setString(1, studentId); int rowsAffected = pstmt.executeUpdate(); pstmt.close(); return rowsAffected > 0; } catch (SQLException | ClassNotFoundException ex) { JOptionPane.showMessageDialog(null, "删除出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); return false; } finally { try { if (conn != null) conn.close(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "关闭连接出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } }
九、修改功能
(一)修改学生信息
1)修改界面
2)通过学号获取学生信息
• 输入不存在的学号
• 输入存在的学号
3)进行修改
4)修改功能代码
private void showupdateStudent() { final JDialog dialog = new JDialog(this, "修改学生信息", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 输入面板和布局 JPanel inputPanel = new JPanel(new GridLayout(6, 2)); inputPanel.add(new JLabel("学号:")); idField = new JTextField(); inputPanel.add(idField); inputPanel.add(new JLabel("姓名:")); nameField = new JTextField(); inputPanel.add(nameField); inputPanel.add(new JLabel("性别:")); sexField = new JTextField(); inputPanel.add(sexField); inputPanel.add(new JLabel("专业:")); specializedField = new JTextField(); inputPanel.add(specializedField); inputPanel.add(new JLabel("生日:")); birthdayField = new JTextField(); inputPanel.add(birthdayField); dialog.getContentPane().add(inputPanel, BorderLayout.CENTER); // 按钮面板 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); // 获取数据按钮 JButton getButton = new JButton("获取数据"); getButton.addActionListener(e -> { String studentId = idField.getText(); if (studentExists(studentId)) { fillStudentInfo(studentId, dialog); // 填充学生信息到文本框 JOptionPane.showMessageDialog(null, "获取成功", "提示", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(dialog, "该学号的学生不存在,请重新检查。", "提示", JOptionPane.ERROR_MESSAGE); } }); buttonPanel.add(getButton); // 确认修改按钮 JButton confirmButton = new JButton("确认修改"); confirmButton.addActionListener(e -> { String studentId = idField.getText(); if (studentExists(studentId)) { updateStudent(dialog); JOptionPane.showMessageDialog(null, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(dialog, "该学号的学生不存在,请重新检查。", "提示", JOptionPane.ERROR_MESSAGE); } }); buttonPanel.add(confirmButton); JButton cancelButton = new JButton("取消"); cancelButton.addActionListener(e -> dialog.dispose()); buttonPanel.add(cancelButton); dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); dialog.setVisible(true);} // 填充学生信息到对话框的文本框 private void fillStudentInfo(String studentId, JDialog dialog) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(uri, user, password); String sql = "SELECT name, sex, specialized, birthday FROM student_info WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, studentId); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { nameField.setText(rs.getString("name")); sexField.setText(rs.getString("sex")); specializedField.setText(rs.getString("specialized")); birthdayField.setText(rs.getString("birthday")); } } catch (ClassNotFoundException | SQLException ex) { JOptionPane.showMessageDialog(dialog, "获取学生信息出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } // 检查学生是否存在 private boolean studentExists(String studentId) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(uri, user, password); String sql = "SELECT COUNT(*) FROM student_info WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, studentId); ResultSet rs = pstmt.executeQuery(); if (rs.next() && rs.getInt(1) > 0) { return true; } } catch (ClassNotFoundException | SQLException ex) { JOptionPane.showMessageDialog(null, "查询出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } return false; } // 传入dialog参数以便在操作后关闭它 private void updateStudent(JDialog dialog) { String id = idField.getText(); String name = nameField.getText(); String sex = sexField.getText(); String specialized = specializedField.getText(); String birthday = birthdayField.getText(); try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(uri, user, password); String sqlStr="UPDATE student_info SET name=?,sex=?,specialized = ?,birthday=? WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sqlStr); pstmt.setString(1, name); pstmt.setString(2, sex); pstmt.setString(3, specialized); pstmt.setString(4, birthday); pstmt.setString(5, id); int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { textArea.append("学生信息更新成功。\n"); } else { textArea.setText("更新失败,未找到匹配的学号。\n"); } } catch (SQLException | ClassNotFoundException ex) { textArea.setText("更新出错:" + ex.getMessage()); } finally { try { if (conn != null) conn.close(); } catch (SQLException ex) { textArea.append("关闭连接出错:" + ex.getMessage()); } } clearInputFields(); // 清空输入框 } private void clearInputFields() { idField.setText(""); nameField.setText(""); sexField.setText(""); specializedField.setText(""); birthdayField.setText(""); } public static void main(String[] args) { EventQueue.invokeLater(() -> new jiemian()); }}
十、源代码汇总
package studentsql;import java.awt.*;import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.sql.*;class LoginDialog1 extends JDialog implements ActionListener { private JTextField usernameField; private JPasswordField passwordField; private JButton loginButton; private JLabel messageLabel; public LoginDialog1(JFrame parent) { super(parent, "登录", true); setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.HORIZONTAL; gc.insets = new Insets(5, 5, 5, 5); gc.gridx = 0; gc.gridy = 0; add(new JLabel("用户名:"), gc); gc.gridx = 1; gc.gridy = 0; usernameField = new JTextField(20); add(usernameField, gc); gc.gridx = 0; gc.gridy = 1; add(new JLabel("密码:"), gc); gc.gridx = 1; gc.gridy = 1; passwordField = new JPasswordField(20); add(passwordField, gc); gc.gridx = 1; gc.gridy = 2; loginButton = new JButton("登录"); loginButton.addActionListener(this); add(loginButton, gc); gc.gridx = 1; gc.gridy = 3; messageLabel = new JLabel(""); messageLabel.setForeground(Color.RED); add(messageLabel, gc); pack(); setLocationRelativeTo(parent); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == loginButton) { String username = usernameField.getText(); String password = new String(passwordField.getPassword()); if (isValidLogin(username, password)) { // 登录成功,关闭登录对话框并继续到主界面操作 dispose(); } else { messageLabel.setText("用户名或密码错误,请重试。"); } } } // 验证登录信息 private boolean isValidLogin(String username, String password) { try { Class.forName("com.mysql.cj.jdbc.Driver"); String uri = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=gbk";//localhost:3306,其中3306是我的数据库接口,下载时mysql的默认接口是3306,但是如果这个接口被其他软件占用的话,会改成另一个接口号,大家根据自身实际修改接口号;“student?"中的student是我新建的数据库名,大家也按需修改。 Connection conn = DriverManager.getConnection(uri, "填用户名", "填数据库密码");//这里两个双引号里的内容大家也按需填写 String sql = "SELECT * FROM user WHERE `user_id`=? AND `key`=?"; // 移除列名周围的单引号 PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, username); pstmt.setString(2, password); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { // 仅检查是否有结果 return true; } } catch (Exception ex) { System.err.println("登录验证出错:" + ex.getMessage()); } return false; }}public class jiemian extends JFrame implements ActionListener { private Connection conn = null; private Statement stmt; private ResultSet rs; private String uri = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=gbk"; private String user = "用户名"; private String password = "数据库密码"; private JTextField idField, nameField, sexField, specializedField, birthdayField; private JButton addButton, deleteButton, updateButton, queryButton; private JTextArea textArea = new JTextArea(10, 30); public jiemian() { // 初始化组件 initializeComponents(); // 设置窗体基本属性 setTitle("学生管理系统"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE);// setVisible(true); } private void initializeComponents() { // 初始化按钮并添加事件监听器 JPanel buttonPanel = new JPanel(new FlowLayout()); addButton = new JButton("添加"); deleteButton = new JButton("删除"); updateButton = new JButton("修改"); queryButton = new JButton("查询"); buttonPanel.add(addButton); buttonPanel.add(deleteButton); buttonPanel.add(updateButton); buttonPanel.add(queryButton); // 添加按钮事件监听器 addButton.addActionListener(this); deleteButton.addActionListener(this); updateButton.addActionListener(this); queryButton.addActionListener(this);// getContentPane().add(inputPanel, "North"); getContentPane().add(buttonPanel, "South");// getContentPane().add(new JScrollPane(textArea), "Center");// setSize(100, 100); setLocationRelativeTo(null); setVisible(true); LoginDialog1 loginDialog = new LoginDialog1(this); loginDialog.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == queryButton) { showquery(); } else if (e.getSource() == addButton) { showInsertStudentDialog(); } else if (e.getSource() == deleteButton) { showDeleteStudent(); } else if (e.getSource() == updateButton) { showupdateStudent(); } } private void showquery() { final JDialog dialog = new JDialog(this, "查询学生", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 查询结果区域 JTextArea queryResultArea = new JTextArea(10, 30); queryResultArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(queryResultArea); dialog.getContentPane().add(scrollPane, BorderLayout.CENTER); // 输入面板,用于存放查询条件输入组件 JPanel inputPanel = new JPanel(new FlowLayout()); JTextField studentIdField = new JTextField(20); studentIdField.setVisible(false); inputPanel.add(studentIdField); dialog.getContentPane().add(inputPanel, BorderLayout.NORTH); // 按钮面板,包含全部查询、单个查询和取消按钮 JPanel buttonPanel = new JPanel(); JButton allQueryButton = new JButton("全部查询"); JButton singleQueryButton = new JButton("单个查询"); JButton cancelButton = new JButton("取消"); allQueryButton.addActionListener(e -> { query("全部查询", "", queryResultArea); queryResultArea.setText(textArea.getText()); }); singleQueryButton.addActionListener(e -> { studentIdField.setVisible(true); dialog.revalidate(); // 重新验证对话框布局 dialog.repaint(); // 重绘对话框 }); cancelButton.addActionListener(e -> dialog.dispose()); buttonPanel.add(allQueryButton); buttonPanel.add(singleQueryButton); buttonPanel.add(cancelButton); dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); // 单个查询 JButton confirmQueryButton = new JButton("确认查询"); confirmQueryButton.addActionListener(e -> { String studentId = studentIdField.getText(); if (!studentId.trim().isEmpty()) { query("单个查询", studentId, queryResultArea); queryResultArea.setText(textArea.getText()); } else { JOptionPane.showMessageDialog(dialog, "请输入学生ID", "提示", JOptionPane.WARNING_MESSAGE); } }); // 动态添加确认查询按钮到输入面板,当单个查询被点击时 singleQueryButton.addActionListener(e -> { inputPanel.add(confirmQueryButton); dialog.revalidate(); dialog.repaint(); }); dialog.setVisible(true); } private void query(String queryType, String studentId,JTextArea queryResultArea) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("数据库驱动加载成功"); conn = DriverManager.getConnection(uri, user, password); String queryStr; PreparedStatement pstmt = null; // 初始化PreparedStatement变量 if ("全部查询".equals(queryType)) { queryStr = "SELECT * FROM student_info"; stmt = conn.createStatement(); } else if ("单个查询".equals(queryType) && !studentId.isEmpty()) { queryStr = "SELECT * FROM student_info WHERE id = ?"; pstmt = conn.prepareStatement(queryStr); // 使用PreparedStatement pstmt.setString(1, studentId); } else { textArea.setText("请选择有效的查询类型或输入学生ID"); return; } ResultSet rs; if (pstmt != null) { // 对于单个查询,使用PreparedStatement执行查询 rs = pstmt.executeQuery(); } else { // 全部查询,使用Statement执行 rs = stmt.executeQuery(queryStr); } StringBuilder sb = new StringBuilder(); boolean hasData = false; while (rs.next()) { hasData = true; String stu_id = rs.getString("id"); String stu_sex = rs.getString("sex"); String stu_name = rs.getString("name"); String stu_specialized = rs.getString("specialized"); String stu_birthday = rs.getString("birthday"); sb.append(stu_id).append("\t").append(stu_sex).append("\t") .append(stu_name).append("\t").append(stu_specialized) .append("\t").append(stu_birthday).append("\n"); } if (hasData) { textArea.setText(sb.toString()); } else if ("单个查询".equals(queryType)) { textArea.setText("未找到该学生ID的记录"); } // 确保PreparedStatement关闭 if (pstmt != null) { pstmt.close(); } stmt.close(); // 如果是全部查询,关闭Statement conn.close(); } catch (SQLException ex) { textArea.setText("查询出错:" + ex.getMessage()); } catch (Exception ex) { textArea.setText("系统错误:" + ex.getMessage()); } } // 添加学生 private void showInsertStudentDialog() { JDialog dialog = new JDialog(this, "添加学生", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 创建输入面板并设置布局 JPanel inputPanel = new JPanel(new GridLayout(10, 10)); inputPanel.add(new JLabel("学号:")); idField = new JTextField(); inputPanel.add(idField); inputPanel.add(new JLabel("姓名:")); nameField = new JTextField(); inputPanel.add(nameField); inputPanel.add(new JLabel("性别:")); sexField = new JTextField(); inputPanel.add(sexField); inputPanel.add(new JLabel("专业:")); specializedField = new JTextField(); inputPanel.add(specializedField); inputPanel.add(new JLabel("生日:")); birthdayField = new JTextField(); inputPanel.add(birthdayField); // 添加输入面板到对话框的中心区域 dialog.getContentPane().add(inputPanel, BorderLayout.CENTER); // 创建按钮面板用于确认和取消按钮 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton confirmButton = new JButton("确认添加"); confirmButton.addActionListener(e -> { // 获取输入值,调用insert方法 insert(); dialog.dispose(); // 关闭对话框 }); buttonPanel.add(confirmButton); JButton cancelButton = new JButton("取消"); cancelButton.addActionListener(e -> dialog.dispose()); // 点击取消时关闭对话框 buttonPanel.add(cancelButton); // 将按钮面板添加到对话框的南侧 dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); dialog.setVisible(true); } private void insert() { String id = idField.getText(); String name = nameField.getText(); String sex = sexField.getText(); String specialized = specializedField.getText(); String birthday = birthdayField.getText(); try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(uri, user, password); String sqlStr = "INSERT INTO student_info(id, sex, name, specialized, birthday) VALUES (?, ?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sqlStr); pstmt.setString(1, id); pstmt.setString(2, sex); pstmt.setString(3, name); pstmt.setString(4, specialized); pstmt.setString(5, birthday); pstmt.executeUpdate(); textArea.append("学生信息添加成功。\n"); } catch (SQLException | ClassNotFoundException ex) { textArea.setText("添加出错:" + ex.getMessage()); } finally { try { if (conn != null) conn.close(); } catch (SQLException ex) { textArea.append("关闭连接出错:" + ex.getMessage()); } } clearInputFields(); // 清空输入框 } private void showDeleteStudent() { JDialog dialog = new JDialog(this, "删除学生", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 创建一个标签和文本框用于输入学号 JLabel idLabel = new JLabel("请输入要删除学生的学号:"); JTextField idTextField = new JTextField(20); JPanel inputPanel = new JPanel(new FlowLayout()); inputPanel.add(idLabel); inputPanel.add(idTextField); dialog.getContentPane().add(inputPanel, BorderLayout.NORTH); // 创建一个标签用于显示操作结果 JLabel resultLabel = new JLabel("", SwingConstants.CENTER); dialog.getContentPane().add(resultLabel, BorderLayout.CENTER); // 添加确认删除按钮 JButton deleteButton = new JButton("确认删除"); deleteButton.addActionListener(e -> { // 获取输入的学号 String studentId = idTextField.getText(); if (!studentId.isEmpty()) { // 执行删除操作,并传入学号参数 boolean deleted = deleteStudent(studentId); if (deleted) { resultLabel.setText("学生信息删除成功。"); } else { resultLabel.setText("删除失败,未找到匹配的学号。"); } } else { JOptionPane.showMessageDialog(dialog, "请输入学号", "提示", JOptionPane.INFORMATION_MESSAGE); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(deleteButton); dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); dialog.setVisible(true); } private boolean deleteStudent(String studentId) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("数据库驱动加载成功"); conn = DriverManager.getConnection(uri, user, password); String sqlStr = "DELETE FROM student_info WHERE id=?"; PreparedStatement pstmt = conn.prepareStatement(sqlStr); pstmt.setString(1, studentId); int rowsAffected = pstmt.executeUpdate(); pstmt.close(); return rowsAffected > 0; } catch (SQLException | ClassNotFoundException ex) { JOptionPane.showMessageDialog(null, "删除出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); return false; } finally { try { if (conn != null) conn.close(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "关闭连接出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } }private void showupdateStudent() { final JDialog dialog = new JDialog(this, "修改学生信息", true); dialog.setSize(900, 400); dialog.setLocationRelativeTo(this); // 输入面板和布局 JPanel inputPanel = new JPanel(new GridLayout(6, 2)); inputPanel.add(new JLabel("学号:")); idField = new JTextField(); inputPanel.add(idField); inputPanel.add(new JLabel("姓名:")); nameField = new JTextField(); inputPanel.add(nameField); inputPanel.add(new JLabel("性别:")); sexField = new JTextField(); inputPanel.add(sexField); inputPanel.add(new JLabel("专业:")); specializedField = new JTextField(); inputPanel.add(specializedField); inputPanel.add(new JLabel("生日:")); birthdayField = new JTextField(); inputPanel.add(birthdayField); dialog.getContentPane().add(inputPanel, BorderLayout.CENTER); // 按钮面板 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); // 获取数据按钮 JButton getButton = new JButton("获取数据"); getButton.addActionListener(e -> { String studentId = idField.getText(); if (studentExists(studentId)) { fillStudentInfo(studentId, dialog); // 填充学生信息到文本框 JOptionPane.showMessageDialog(null, "获取成功", "提示", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(dialog, "该学号的学生不存在,请重新检查。", "提示", JOptionPane.ERROR_MESSAGE); } }); buttonPanel.add(getButton); // 确认修改按钮 JButton confirmButton = new JButton("确认修改"); confirmButton.addActionListener(e -> { String studentId = idField.getText(); if (studentExists(studentId)) { updateStudent(dialog); JOptionPane.showMessageDialog(null, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(dialog, "该学号的学生不存在,请重新检查。", "提示", JOptionPane.ERROR_MESSAGE); } }); buttonPanel.add(confirmButton); JButton cancelButton = new JButton("取消"); cancelButton.addActionListener(e -> dialog.dispose()); buttonPanel.add(cancelButton); dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH); dialog.setVisible(true);} // 填充学生信息到对话框的文本框 private void fillStudentInfo(String studentId, JDialog dialog) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(uri, user, password); String sql = "SELECT name, sex, specialized, birthday FROM student_info WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, studentId); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { nameField.setText(rs.getString("name")); sexField.setText(rs.getString("sex")); specializedField.setText(rs.getString("specialized")); birthdayField.setText(rs.getString("birthday")); } } catch (ClassNotFoundException | SQLException ex) { JOptionPane.showMessageDialog(dialog, "获取学生信息出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } // 检查学生是否存在 private boolean studentExists(String studentId) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(uri, user, password); String sql = "SELECT COUNT(*) FROM student_info WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, studentId); ResultSet rs = pstmt.executeQuery(); if (rs.next() && rs.getInt(1) > 0) { return true; } } catch (ClassNotFoundException | SQLException ex) { JOptionPane.showMessageDialog(null, "查询出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } return false; } // 传入dialog参数以便在操作后关闭它 private void updateStudent(JDialog dialog) { String id = idField.getText(); String name = nameField.getText(); String sex = sexField.getText(); String specialized = specializedField.getText(); String birthday = birthdayField.getText(); try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(uri, user, password); String sqlStr="UPDATE student_info SET name=?,sex=?,specialized = ?,birthday=? WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sqlStr); pstmt.setString(1, name); pstmt.setString(2, sex); pstmt.setString(3, specialized); pstmt.setString(4, birthday); pstmt.setString(5, id); int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { textArea.append("学生信息更新成功。\n"); } else { textArea.setText("更新失败,未找到匹配的学号。\n"); } } catch (SQLException | ClassNotFoundException ex) { textArea.setText("更新出错:" + ex.getMessage()); } finally { try { if (conn != null) conn.close(); } catch (SQLException ex) { textArea.append("关闭连接出错:" + ex.getMessage()); } } clearInputFields(); // 清空输入框 } private void clearInputFields() { idField.setText(""); nameField.setText(""); sexField.setText(""); specializedField.setText(""); birthdayField.setText(""); } public static void main(String[] args) { EventQueue.invokeLater(() -> new jiemian()); }}
以上就是博主课程实践的全部内容,希望能对广大求学者有所帮助!
未经允许,请勿转载