以下是一个示例的Java代码,演示如何通过编写GUI界面向”student”表中插入和删除若干数据记录:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class StudentDatabaseGUI extends JFrame {
private JLabel lblName, lblID;
private JTextField txtName, txtID;
private JButton btnInsert, btnDelete;
public StudentDatabaseGUI() {
super("Student Database");
// 创建界面元素
lblName = new JLabel("Name:");
lblID = new JLabel("ID:");
txtName = new JTextField(20);
txtID = new JTextField(10);
btnInsert = new JButton("Insert");
btnDelete = new JButton("Delete");
// 设置布局管理器
setLayout(new FlowLayout());
// 添加界面元素到容器
add(lblName);
add(txtName);
add(lblID);
add(txtID);
add(btnInsert);
add(btnDelete);
// 添加事件监听器
btnInsert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = txtName.getText();
String id = txtID.getText();
// 调用插入方法将数据插入数据库
insertData(name, id);
// 清空文本框内容
txtName.setText("");
txtID.setText("");
}
});
btnDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String id = txtID.getText();
// 调用删除方法从数据库中删除对应的数据记录
deleteData(id);
// 清空文本框内容
txtID.setText("");
}
});
// 设置窗口属性
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// 插入数据到数据库的方法
private void insertData(String name, String id) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password");
Statement stmt = conn.createStatement();
String query = "INSERT INTO student (name, id) VALUES ('" + name + "', '" + id + "')";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Data inserted successfully.");
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// 删除数据记录的方法
private void deleteData(String id) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password");
Statement stmt = conn.createStatement();
String query = "DELETE FROM student WHERE id='" + id + "'";
int result = stmt.executeUpdate(query);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data deleted successfully.");
} else {
JOptionPane.showMessageDialog(this, "No matching record found.");
}
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StudentDatabaseGUI().setVisible(true);
}
});
}
}
请注意,上述代码中的database_name
、username
和password
需要根据你自己的数据库配置进行修改。此外,建议使用PreparedStatement来防止SQL注入攻击,这里简化示例代码并未使用PreparedStatement。务必根据实际情况进行安全性考虑和错误处理。
内容由零声教学AI助手提供,问题来源于学员提问