MySQL5.5
时间: 2024-02-25 19:54:25 浏览: 21
好的,以下是一个基于MySQL 5.5和Java Swing的学生成绩查询功能的代码示例:
```
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ScoreQuery extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField studentIdText;
private JButton queryButton;
private JLabel resultLabel;
private JPanel mainPanel;
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "yourpassword";
public ScoreQuery() {
super("学生成绩查询");
// 初始化GUI组件
studentIdText = new JTextField(10);
queryButton = new JButton("查询");
queryButton.addActionListener(this);
resultLabel = new JLabel("查询结果将在这里显示。");
mainPanel = new JPanel();
mainPanel.add(new JLabel("请输入要查询的学生学号:"));
mainPanel.add(studentIdText);
mainPanel.add(queryButton);
mainPanel.add(resultLabel);
// 将GUI组件添加到窗口中
getContentPane().add(mainPanel, BorderLayout.CENTER);
// 设置窗口属性
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 150);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == queryButton) {
String studentId = studentIdText.getText().trim();
if (studentId.isEmpty()) {
resultLabel.setText("请输入学生学号!");
return;
}
try {
// 连接MySQL数据库
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
// 执行查询
String sql = "SELECT subject, score FROM scores WHERE student_id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, studentId);
ResultSet rs = stmt.executeQuery();
// 处理查询结果
StringBuilder sb = new StringBuilder();
while (rs.next()) {
String subject = rs.getString("subject");
int score = rs.getInt("score");
sb.append(subject).append(": ").append(score).append("\n");
}
if (sb.length() == 0) {
resultLabel.setText("未找到该学生的成绩!");
} else {
resultLabel.setText(sb.toString());
}
// 关闭连接和查询对象
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
resultLabel.setText("数据库驱动加载失败!");
} catch (SQLException ex) {
ex.printStackTrace();
resultLabel.setText("数据库连接或查询失败!");
}
}
}
public static void main(String[] args) {
new ScoreQuery();
}
}
```
这个示例中,我们使用了JDBC连接MySQL数据库,查询学生的成绩,并将查询结果显示在GUI中。你需要修改其中的数据库连接信息和查询语句,以适应你自己的数据库和数据表结构。