Keyword Duplication Elimination

I have a table with a unique primary key column called id . Sometimes, when I execute an INSERT request, I get an error because the id value is already in use.

Is it possible to catch this particular error with try and catch ?

+8
java mysql try-catch
source share
1 answer

It seems that mysql is throwing error code 1062 for the duplicate primary key. You can check the error code for sql exception:

 public static final int MYSQL_DUPLICATE_PK = 1062; try{ //code that throws sql exception } catch(SQLException e){ if(e.getErrorCode() == MYSQL_DUPLICATE_PK ){ //duplicate primary key } } 

Please note that this approach is not a cross-database provider, as different manufacturers may have different error codes for duplicating a PC.

+9
source share

All Articles