Here i have a problem in my code when i want to delete a record:(student) from database and i know there is a related key
but i cannot solve this problem i tried deleting student that on the stage and this is the code:
x
public int deleteStudentStage(int stdId) //delete student by stId
{
DatabaseConnection dbconn = new DatabaseConnection();
Connection conn = dbconn.getConn();
PreparedStatement pStm = null;
int rows = 0;
try
{
//String sql = "DELETE FROM STUDENT_STAGE WHERE STUDENT_ID = ? AND STAGE_ID = ?";
String sql = "DELETE FROM STUDENT WHERE ID = ? ";
pStm = conn.prepareStatement(sql);
//fill SQL parameters from student: //
pStm.setInt(1, stdId);
// excute //
rows = pStm.executeUpdate();
}
catch (SQLException ex)
{
System.out.println("SQLException: " + ex.getMessage());
}
finally
{
try {
conn.commit();
pStm.close();
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());;
}
}
return rows;
}
Advertisement
Answer
can you give more information about it?, normally that happens when you have a foregin key, in this case of the table STUDENT, you need to delete all rows in the other table first before delete STUDENT, you also can solve it, adding a delete on cascade, when you create the foregin key
you need then do the following:
DELETE FROM STUDENT_STAGE WHERE STUDENT_ID=?
DELETE FROM STUDENT WHERE ID = ?
also you can update the foregin key in the table for cascade delete:
ALTER TABLE STUDENT_STAGE DROP FOREIGN KEY STUDENT_STAGE_FK;
ALTER TABLE STUDENT_STAGE ADD CONSTRAINT STUDENT_STAGE_FK FOREIGN KEY STUDENT_ID REFERENCES STUDENT (ID) ON DELETE CASCADE ON UPDATE CASCADE;
Whith the update of the foregin key, deleting a studen, you also delete all the information of this student in the table STUDENT_STAGE