7. 利用JavaGUI 和JDBC 编程实现学生成绩查询功能。(输入学生学号,即可查询到该学 生的所有成绩)
时间: 2024-03-09 18:45:51 浏览: 62
好的,下面是一个简单的JavaGUI和JDBC编程实现学生成绩查询功能的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class ScoreQueryGUI extends JFrame implements ActionListener {
private JLabel label;
private JTextField textField;
private JButton button;
private JTextArea textArea;
private Connection conn;
public ScoreQueryGUI() {
// 初始化窗口
setTitle("学生成绩查询");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 添加组件
label = new JLabel("请输入学生学号:");
textField = new JTextField(10);
button = new JButton("查询");
button.addActionListener(this);
textArea = new JTextArea(10, 30);
textArea.setEditable(false);
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
panel.add(button);
add(panel, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
// 连接数据库
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String id = textField.getText().trim();
if (id.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入学号");
return;
}
try {
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM score WHERE id='" + id + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
String name = rs.getString("name");
int chinese = rs.getInt("chinese");
int math = rs.getInt("math");
int english = rs.getInt("english");
int total = rs.getInt("total");
textArea.setText("姓名: " + name + "\n"
+ "语文: " + chinese + "\n"
+ "数学: " + math + "\n"
+ "英语: " + english + "\n"
+ "总分: " + total);
} else {
JOptionPane.showMessageDialog(this, "无此学生");
}
rs.close();
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
ScoreQueryGUI gui = new ScoreQueryGUI();
gui.setVisible(true);
}
}
```
在这个示例代码中,我们使用了Java的GUI库Swing来构建用户界面,使用了JDBC来连接MySQL数据库并查询学生成绩。在事件处理器中,我们首先获取用户输入的学号,然后构造SQL语句并执行查询操作。如果查询成功,我们则将查询结果填充到文本区域中显示给用户。如果查询失败,则弹出提示框告知用户。
阅读全文