capture duplicity error in mysql with java

Asked

Viewed 88 times

0

I’m trying to show a message that there is already a registered id, but it falls in the catch that shows:

 com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'idusuario' 

i want to show that there is already a registered id.

 try {
        conexao=ConexaoBanco.conector();
        pst=conexao.prepareStatement(sql);
        pst.setString(1,nomeusuario);
        pst.setString(2,senha);  
        try{            
            pst.setInt(3,Integer.parseInt(idusuario));
        }catch(SQLException x){
            JOptionPane.showMessageDialog(null,"ID JÁ CADASTRADA");
        }
        pst.setString(4,perfil);     
        pst.setString(5,nome);          
        pst.executeUpdate();
        return true;
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null,e);
        return false;   
    }

( My username is login, so there is no confusion).

1 answer

1


You are using Try/catch in the wrong place. The exception is thrown in the following line:

   pst.executeUpdate();

You can use the catch below to capture the most specific exception you want:

} catch (MySQLIntegrityConstraintViolationException e) {
     JOptionPane.showMessageDialog(null,"ID JÁ CADASTRADA");
} catch (SQLException e) {
     JOptionPane.showMessageDialog(null,e);
     return false;   
}
  • So, I cannot have equal idusuario or username. How would I separate the two errors to show the "right" error for the user?

  • See my issue.

  • at the time posted I also posted :p, I will take a look.

  • 1

    I hope it works, because I can not improve the answer. I entered the Sopt by reflection, I am slightly "high". With the information of where the exception is shot you should already be able to do something about it. Good luck.

  • so I put this and it really works capture, but until pro user name he is playing on screen "id already registered"

  • I was hoping to help with that last question, but thanks anyway.

  • 1

    Only if I try to do something. The most innocuous I can think of is to use the getMessage() the exception to take the name of the already registered field and mount a message to the user based on it. Or save in a variable the name of the field being assigned and base on this variable to show the message to the user within the exception handling.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.