JDBC读取学生信息功能的UI
时间: 2023-08-14 08:07:21 浏览: 42
以下是一个简单的JDBC读取学生信息功能的UI示例:
```java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class StudentInfoUI extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField tfName, tfId, tfAge, tfAddress;
private JButton btnSearch;
private JTextArea taResult;
public StudentInfoUI() {
super("学生信息查询");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
JLabel lblName = new JLabel("姓名:");
tfName = new JTextField(10);
JLabel lblId = new JLabel("学号:");
tfId = new JTextField(10);
JLabel lblAge = new JLabel("年龄:");
tfAge = new JTextField(10);
JLabel lblAddress = new JLabel("地址:");
tfAddress = new JTextField(10);
JPanel pnlInput = new JPanel();
pnlInput.setLayout(new GridLayout(2, 4));
pnlInput.add(lblName);
pnlInput.add(tfName);
pnlInput.add(lblId);
pnlInput.add(tfId);
pnlInput.add(lblAge);
pnlInput.add(tfAge);
pnlInput.add(lblAddress);
pnlInput.add(tfAddress);
btnSearch = new JButton("查询");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = tfName.getText();
String id = tfId.getText();
String age = tfAge.getText();
String address = tfAddress.getText();
String query = "SELECT * FROM student WHERE 1=1";
if (!name.isEmpty()) {
query += " AND name='" + name + "'";
}
if (!id.isEmpty()) {
query += " AND id='" + id + "'";
}
if (!age.isEmpty()) {
query += " AND age=" + age;
}
if (!address.isEmpty()) {
query += " AND address='" + address + "'";
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/student", "root", "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
taResult.setText("");
while (rs.next()) {
taResult.append(rs.getString("name") + "\t" +
rs.getString("id") + "\t" +
rs.getInt("age") + "\t" +
rs.getString("address") + "\n");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
taResult = new JTextArea();
JScrollPane scrollPane = new JScrollPane(taResult);
JPanel pnlButton = new JPanel();
pnlButton.add(btnSearch);
setLayout(new BorderLayout());
add(pnlInput, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
StudentInfoUI ui = new StudentInfoUI();
ui.setVisible(true);
}
}
```
这个UI界面包含了四个文本框和一个查询按钮,用户可以在文本框中输入学生的姓名、学号、年龄和地址,然后点击查询按钮,程序就会根据用户输入的条件从数据库中读取相应的学生信息,并在文本域中显示出来。注意,这个示例中使用的是MySQL数据库,需要先安装和配置好MySQL数据库,并且导入一个名为`student`的数据库和一个名为`student`的表,表中包含四个字段:`name`、`id`、`age`和`address`。