I have a table with a unique primary key column called id
. Sometimes when I perform an INSERT
query I get an error because the id
value is already used.
Can I catch this specific error with try
and catch
?
Looks like mysql is throwing 1062 error code for duplicate primary key. You can check the error code for your 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
}
}
Notice that this approach is not cross database vendor, because different vendors might have different error codes for duplicate PK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With