How do you correctly catch a MySQLIntegrityConstraintViolationException?

I’m working on a web application, and the moment I submit forms that are unique to the user,

 MySQLIntegrityConstraintViolationException Duplicate entry -'username ' 
for key 'PRIMARY'

I am well aware why this happens because I am trying to enter a double entry into the database with the same primary key. I would appreciate no comment on this, as this may be redundant.

What I'm really asking is how should I handle this. I tried to catch this exception, but apparently my lack of experience caught up with me.

I would be grateful for your help.

Is there a better way to check for duplicate records in a database?

For example, should I do what I do when checking for duplicate items and just do a database check for a matching username and password?

thank

+3
source share
3 answers

As a rule, if it is possible to avoid exception exceptions, since they are a heavy mechanism for managing the program workflow. You should only use them to track errors and irregular activities / situations. All this means that if you catch an exception, the only thing you can do is write a little more, wrap the exception in another exception, and ultimately run some logic program.

, . , , - ... , , ...

, , , .

+1

, , , , .

+1

I also had the same problem, try handling the exception with catch (MySQLIntegrityConstraintViolationException sql). But don't forget that there are two types for JDBC: MySQLIntegrityConstraintViolationException , one for JDBC4. Therefore, I recommend catching both in two separate try catch methods.

0
source

Source: https://habr.com/ru/post/1746225/


All Articles