Use SQL Server 2017 with Management Studio and Java 8.
I have a database about movies and I receive an error when trying to delete a movie that is referring to another table that acts as an intermediate.
Diagram (example values in red):
Error:
SQLServerException: The DELETE statement conflicted with the REFERENCE constraint "FK_PELICULAS_GENEROS_PELICULAS". The conflicted occurred in database "industriaCine", table "dbo.PELICULAS_GENEROS", column "movie_id".
Code to delete:
public boolean eliminarPelicula(int id) {
sSQL = "DELETE FROM peliculas WHERE id_pelicula=?";
boolean resultado;
// Java 7 try-with-resources
try (PreparedStatement pstm = con.prepareStatement(sSQL)) {
pstm.setInt(1, id);
pstm.executeUpdate();
resultado = true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "SQLException:\n" + e, "Error: eliminarPelicula()", JOptionPane.ERROR_MESSAGE);
resultado = false;
}
return resultado;
}
The Foreign Key I did it this way:
ALTER TABLE PELICULAS_GENEROS ADD CONSTRAINT FK_PELICULAS_GENEROS_PELICULAS FOREIGN KEY (id_pelicula) REFERENCES PELICULAS(id_pelicula);
The idea is that if I delete a id_pelicula
, we will also delete id_pelicula
from table PELICULAS_GENEROS
. Example (as in the photo above), if I delete the movie with id_pelicula = 2
, the error appears.
First time I do something like this.
What's happening? Why the error? Should I change something in SQL Management Studio in references?.
I'm lost, thanks in advance for the help.