2
The program I’m doing requires a deletion of users from the bank!
In the code I determine:
Menu:
static private void Excluir(Connection con) throws SQLException
{
String cpf;
Scanner s = new Scanner(System.in);
Cliente cli = new Cliente();
System.out.println("Informe o CPF a ser Excluido:");
cli.cpf = s.next();
System.out.println();
cli.ExcluirPess(cli, con);
}
In client class I determine:
public void ExcluirPess(Cliente cli, Connection con) throws SQLException {
String sql = "delete from Cliente where CPF_cliente = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, cli.getCpf());
stmt.executeUpdate();
stmt.close();
}
I tidied as demonstrated, but the exclusion is not yet made! The fact where in the bank to PK CPF_cliente
was FK
in Endereco
and Telefone
, interferes with the exclusion?
I guess instead of
cli.getCpf()
will becli.cpf
.– Piovezan
@Piovezan is possible, can not be sure because the OP did not show the Client class, however cli.Cpf is more guaranteed to work. I’ve changed as you suggest.
– Math
@Math Thanks, as you said it really is necessary to delete first the
FK
then directly delete thePK
table Client– Bruno
@Bruno, I believe you’ve ruled it out through preparedstatement, the same way I would. Just in terms of information, there is another way to do that, would be the
Stored Procedures
, that automatically deletes the Fks from the record you delete, however I ended up not quoting in the answer for not getting too long and why it might not be interesting for you. Just know that there is this other option, if you are ever interested.– Math
@Math didn’t know this other way of deleting
FKs
, by the way is a much easier option to use. Thank you for adding this other option.– Bruno
@Bruno after learning to make them can say that it is easier, however depending on the size of your application you will choose not to have to learn a new command, everything depends on what you are looking for.
– Math
@Math understand, as my application is involving college, it would not be good to fit the
Stored Procedures
. Even so it is good to know other ways to effect exclusions, will help a lot in the future market!– Bruno
In fact, you don’t even need to create a Stored Procedures 90% of the data bands I know there is a Cascate on Delete option, which means when we set FK we say how it reacts to deletion and modification, the options are to ignore, prevent or cascade, in the cascade option you excluding the FK all those who have it as a foreign key will also be deleted. <pre>FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE,<code> Just one example.
– Marcelo Vasconcelos