Search code examples
javasqlsql-serverjdbcmssql-jdbc

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


There's a table name "Student". The request is to write a function that tell user to input a student's ID. If such ID is found, delete that student record, otherwise print "Record not found".

Table structure:
id || fullName || gender || dob

This is my code. Whenever I try to run, it always show this error: The value is not set for the parameter number 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());
        }
    }

Solution

  • Why even SELECT the student first? Just delete it. Skip the first query. Your console output can be implemented like this:

    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.");
    }