21xrx.com
2025-04-26 20:20:13 Saturday
文章检索 我的文章 写文章
用Java实现学生信息管理系统
2023-06-13 09:58:09 深夜i     19     0
Java 学生信息管理系统 JDBC Swing

学生信息管理系统是每个学校都必须的一项软件,它能够帮助教师和管理员管理学生的基本信息,比如个人信息、成绩、奖励等。这些信息必须能够方便地更新和查看,以便于教学的顺利开展。在这篇文章中,我们将介绍如何用Java来实现一个学生信息管理系统。

首先,我们需要创建一个数据库来存储学生信息,我们将使用MySQL数据库。我们需要在数据库中创建一个名为“students”的表,其中包括学生的基本信息、成绩、奖励等字段。然后,我们需要用Java代码来连接数据库,并且从数据库中查询、添加、更新和删除信息。这些操作将使用Java中的JDBC API来实现。

下面是一个示例代码,它可以连接MySQL数据库并且查询学生的基本信息:

java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StudentManager {
 
 public static void main(String[] args) {
  
  // JDBC driver name and database URL
  final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
  final String DB_URL = "jdbc:mysql://localhost/students";
  // Database credentials
  final String USER = "username";
  final String PASS = "password";
  
  Connection conn = null;
  Statement stmt = null;
  
  try {
   // Register JDBC driver
   Class.forName("com.mysql.jdbc.Driver");
   // Open a connection
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
   // Execute a query
   System.out.println("Creating statement...");
   stmt = conn.createStatement();
   String sql;
   sql = "SELECT id, name, age FROM students";
   ResultSet rs = stmt.executeQuery(sql);
   // Extract data from result set
   while(rs.next()){
    int id = rs.getInt("id");
    String name = rs.getString("name");
    int age = rs.getInt("age");
    // Display values
    System.out.print("ID: " + id);
    System.out.print(", Name: " + name);
    System.out.println(", Age: " + age);
   }
   // Clean-up environment
   rs.close();
   stmt.close();
   conn.close();
  } catch(SQLException se) {
   // Handle errors for JDBC
   se.printStackTrace();
  } catch(Exception e) {
   // Handle errors for Class.forName
   e.printStackTrace();
  } finally {
   // finally block used to close resources
   try{
    if(stmt!=null) stmt.close();
   } catch(SQLException se2)
    // nothing we can do
   try {
    if(conn!=null) conn.close();
   } catch(SQLException se){
    se.printStackTrace();
   } // end finally try
  } // end try
 } // end main
} // end StudentManager

以上代码可以查询“students”表中的所有数据,并且将其输出到控制台。通过类似的方式,可以实现添加、更新和删除数据的功能。

最后,我们需要在图形用户界面上实现这些功能。Java中有很多GUI框架可以使用,例如Swing和JavaFX。我们可以用Swing来实现一个简单的学生信息管理系统界面,代码如下:

java
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class StudentGUI {
 // JDBC driver name and database URL
 final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 final String DB_URL = "jdbc:mysql://localhost/students";
 // Database credentials
 final String USER = "username";
 final String PASS = "password";
 private JFrame frame;
 private JTextField idTextField;
 private JTextField nameTextField;
 private JTextField ageTextField;
 private JTextArea infoTextArea;
 private JButton addButton;
 private JButton updateButton;
 private JButton deleteButton;
 private JButton queryButton;
 public static void main(String[] args) {
  try {
   StudentGUI window = new StudentGUI();
   window.frame.setVisible(true);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 public StudentGUI() {
  initialize();
  addButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    addStudent();
   }
  });
  updateButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    updateStudent();
   }
  });
  deleteButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    deleteStudent();
   }
  });
  queryButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    queryStudent();
   }
  });
 }
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(100, 100, 450, 300);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().setLayout(null);
  JLabel idLabel = new JLabel("ID");
  idLabel.setBounds(10, 10, 100, 20);
  frame.getContentPane().add(idLabel);
  idTextField = new JTextField();
  idTextField.setBounds(120, 10, 100, 20);
  frame.getContentPane().add(idTextField);
  idTextField.setColumns(10);
  JLabel nameLabel = new JLabel("Name");
  nameLabel.setBounds(10, 40, 100, 20);
  frame.getContentPane().add(nameLabel);
  nameTextField = new JTextField();
  nameTextField.setBounds(120, 40, 100, 20);
  frame.getContentPane().add(nameTextField);
  nameTextField.setColumns(10);
  JLabel ageLabel = new JLabel("Age");
  ageLabel.setBounds(10, 70, 100, 20);
  frame.getContentPane().add(ageLabel);
  ageTextField = new JTextField();
  ageTextField.setBounds(120, 70, 100, 20);
  frame.getContentPane().add(ageTextField);
  ageTextField.setColumns(10);
  addButton = new JButton("Add");
  addButton.setBounds(10, 100, 80, 20);
  frame.getContentPane().add(addButton);
  updateButton = new JButton("Update");
  updateButton.setBounds(100, 100, 80, 20);
  frame.getContentPane().add(updateButton);
  deleteButton = new JButton("Delete");
  deleteButton.setBounds(190, 100, 80, 20);
  frame.getContentPane().add(deleteButton);
  queryButton = new JButton("Query");
  queryButton.setBounds(280, 100, 80, 20);
  frame.getContentPane().add(queryButton);
  infoTextArea = new JTextArea();
  infoTextArea.setBounds(10, 130, 400, 120);
  frame.getContentPane().add(infoTextArea);
 }
 private void addStudent() {
  Connection conn = null;
  Statement stmt = null;
  try {
   Class.forName(JDBC_DRIVER);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
   stmt = conn.createStatement();
   String sql = "INSERT INTO students (id, name, age) VALUES (" +
    idTextField.getText() + ", '" +
    nameTextField.getText() + "', " +
    ageTextField.getText() + ")";
   stmt.executeUpdate(sql);
   infoTextArea.setText("Add student successfully!");
  } catch (SQLException se) {
   se.printStackTrace();
   infoTextArea.setText("Add student failed: " + se.getMessage());
  } catch (Exception e) {
   e.printStackTrace();
   infoTextArea.setText("Add student failed: " + e.getMessage());
  } finally {
   try {
    if (stmt != null) stmt.close();
   } catch (SQLException se)
   
   try {
    if (conn != null) conn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
 }
 private void updateStudent() {
  Connection conn = null;
  Statement stmt = null;
  try {
   Class.forName(JDBC_DRIVER);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
   stmt = conn.createStatement();
   String sql = "UPDATE students SET name='" +
    nameTextField.getText() + "', age=" +
    ageTextField.getText() + " WHERE id=" +
    idTextField.getText();
   int rows = stmt.executeUpdate(sql);
   if (rows == 0) {
    infoTextArea.setText("Update student failed: no student exist with this ID.");
   } else {
    infoTextArea.setText("Update student successfully!");
   }
  } catch (SQLException se) {
   se.printStackTrace();
   infoTextArea.setText("Update student failed: " + se.getMessage());
  } catch (Exception e) {
   e.printStackTrace();
   infoTextArea.setText("Update student failed: " + e.getMessage());
  } finally {
   try {
    if (stmt != null) stmt.close();
   } catch (SQLException se)
   
   try {
    if (conn != null) conn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
 }
 private void deleteStudent() {
  Connection conn = null;
  Statement stmt = null;
  try {
   Class.forName(JDBC_DRIVER);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
   stmt = conn.createStatement();
   String sql = "DELETE FROM students WHERE id=" + idTextField.getText();
   int rows = stmt.executeUpdate(sql);
   if (rows == 0) {
    infoTextArea.setText("Delete student failed: no student exist with this ID.");
   } else {
    infoTextArea.setText("Delete student successfully!");
   }
  } catch (SQLException se) {
   se.printStackTrace();
   infoTextArea.setText("Delete student failed: " + se.getMessage());
  } catch (Exception e) {
   e.printStackTrace();
   infoTextArea.setText("Delete student failed: " + e.getMessage());
  } finally {
   try {
    if (stmt != null) stmt.close();
   } catch (SQLException se)
   
   try {
    if (conn != null) conn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
 }
 private void queryStudent() {
  Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null;
  try {
   Class.forName(JDBC_DRIVER);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
   stmt = conn.createStatement();
   String sql = "SELECT * FROM students";
   rs = stmt.executeQuery(sql);
   StringBuilder sb = new StringBuilder();
   sb.append("ID\tName\tAge\n");
   while (rs.next()) {
    sb.append(rs.getInt("id")).append('\t')
     .append(rs.getString("name")).append('\t')
     .append(rs.getInt("age")).append('\n');
   }
   infoTextArea.setText(sb.toString());
  } catch (SQLException se) {
   se.printStackTrace();
   infoTextArea.setText("Query students failed: " + se.getMessage());
  } catch (Exception e) {
   e.printStackTrace();
   infoTextArea.setText("Query students failed: " + e.getMessage());
  } finally {
   try {
    if (rs != null) rs.close();
   } catch (SQLException se)
   
   try {
    if (stmt != null) stmt.close();
   } catch (SQLException se)
   
   try {
    if (conn != null) conn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
 }
}

我们可以看到,使用Swing可以方便地实现一个图形化界面,并且将按钮事件和数据库操作联系起来,实现学生信息的添加、更新、删除和查询。

从上述代码可以发现,Java语言是一种非常灵活和高效的编程语言,尤其适合做企业级应用。学生信息管理系统只是Java应用程序的小小一例,但它背后所使用的技术和思想可以帮助我们更深入地理解Java开发的本质。

  
  
下一篇: 的使用和优化

评论区

请求出错了