JAVA学生信息管理系统连接Mysql的GUI界面代码
时间: 2023-12-14 13:04:41 浏览: 169
以下是使用Java Swing编写的学生信息管理系统连接MySQL数据库的GUI界面代码示例:
```java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class StudentManagementSystem extends JFrame {
private JPanel contentPane;
private JTextField txtName;
private JTextField txtID;
private JTable table;
private DefaultTableModel model;
private Connection conn;
private Statement stmt;
private ResultSet rs;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StudentManagementSystem frame = new StudentManagementSystem();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public StudentManagementSystem() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
setTitle("Student Management System");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
txtName = new JTextField();
panel.add(txtName);
txtName.setColumns(10);
txtID = new JTextField();
panel.add(txtID);
txtID.setColumns(10);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
search();
}
});
panel.add(btnSearch);
model = new DefaultTableModel();
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/students", "root", "password");
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
private void search() {
String name = txtName.getText();
String id = txtID.getText();
String sql = "SELECT * FROM students WHERE name LIKE '%" + name + "%' AND id LIKE '%" + id + "%'";
try {
rs = stmt.executeQuery(sql);
while (rs.next()) {
String[] row = { rs.getString("id"), rs.getString("name"), rs.getString("gender"), rs.getString("age"), rs.getString("major") };
model.addRow(row);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们使用MySQL数据库来存储和管理学生信息。在GUI界面中,用户可以输入学生姓名和学号来搜索学生信息。当用户点击“搜索”按钮时,程序将连接到MySQL数据库并执行相应的SQL查询语句,然后将查询结果显示在表格中。
需要注意的是,为了让程序能够连接到MySQL数据库,我们需要将MySQL JDBC驱动程序添加到项目的类路径中。可以从MySQL官网下载最新的MySQL JDBC驱动程序,并将其复制到项目的lib目录下。
阅读全文