JDBC:如何使用 PreparedStatement 从 table 中删除特定记录?

JDBC: How do I delete a specific record from table using PreparedStatement?

有一个 table 名字 "Student"。请求是编写一个函数,告诉用户输入学生 ID。如果找到这样的ID,删除该学生记录,否则打印"Record not found".

Table结构:
编号 ||全名 ||性别 ||多布

这是我的代码。每当我尝试 运行 时,它总是显示此错误:未为参数编号 1 设置值。

public void deleteStudent() {
        System.out.println("Enter the Student's ID you want to delete: ");
        Scanner sc = new Scanner(System.in);
        int id = sc.nextInt();

        try (
                Connection connect = DriverManager.getConnection(ConnectToProperties.getConnection());
                PreparedStatement ps = connect.prepareStatement("SELECT from Student WHERE id = ?");
                ResultSet rs = ps.executeQuery();
                PreparedStatement psDel = connect.prepareStatement("DELETE from Student WHERE id = ?");
            )

        {       
            ps.setInt(1, id);
            if(rs.next()) {
                psDel.setInt(1, id);
                psDel.executeUpdate();
                System.out.println("Record deleted successfully.");
            } else {
                System.out.println("Record not found.");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

为什么还要 SELECT 学生先?只需删除它。跳过第一个查询。您的控制台输出可以这样实现:

try (PreparedStatement psDel = connect.prepareStatement(
    "DELETE FROM Student WHERE id = ?")
) {
    psDel.setInt(1, id);

    if (psDel.executeUpdate() > 0)
        System.out.println("Record deleted successfully.");
    else
        System.out.println("Record not found.");
}