Java Mysql Integrity Constraint Violation Exception
Solution 1
In order to catch a specific SQLException, you need to compare against SQL state using getSQLState()
method. Ex: SQL State 23 for Data Integrity violation.
catch (SQLException ex) {
if (ex.getSQLState().startsWith("23")) {
JOptionPane.showMessageDialog(null, "Duplicate");
}
}
Solution 2
you can not use
MySQLIntegrityConstraintViolationException directly.
Because no exception available in java with that name.
try this
try {
}
catch (DataIntegrityViolationException ex) {
.....
}
and then get the error code using ex.Then compare it
Solution 3
For those checking later, you might either choose to check instance type as:
try {
...
} catch (Exception e) {
if (e instanceof SQLIntegrityConstraintViolationException) {
// duplicate record or alike problem
}
}
amal
Updated on June 04, 2022Comments
-
amal almost 2 years
My Swing applications throws few exceptions. I tried to catch Integrity Constraint Violation Exception and display message "Duplicate ID". But when that happened, without catching it here: catch(MySQLIntegrityConstraintViolationException ex) it goes to catch (SQLException ex). What I want to do is, catch Integrity Violation exception and display user friendly message instead of technical message comes from ex.getMessage(). How do I do this?
ShippmentTransfer shipTrns = new ShippmentTransfer(shipID, GIN, issueDate, ToStore, itemName, Qty, Driver, Vehicle); int res = ShipmentTansController.addShipGIN(shipTrns); if (res > 0) { JOptionPane.showMessageDialog(null, "Record Added"); resetAll(); } } catch (DataIntegrityViolationException ex) { JOptionPane.showMessageDialog(null, "Duplicate ID"); } catch (ClassNotFoundException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.gets); } }
-
amal about 11 yearsThnx for your response. Then how do I catch the Integrity Constraint Violation Exception? Do you have any idea?
-
PSR about 11 yearstry to get the name of exception using ex.Then compare
-
PSR about 11 yearstry to debug ex when raised the exception.What it contains when IntegrityVoilationException raises and other raised.
-
amal about 11 yearsSure. I ll try in that way.
-
amal about 11 yearsFinally managed to sort it out. I used method getSQLState() produces specific error code. Ex. 23 for Data Integrity violation. if(ex.getSQLState().startsWith("23")){ Anyway I appreciate your effort to help me.
-
PSR about 11 years@user2033382 if you got the solution with my answer please accept this as answer
-
amal about 11 yearsI tried using your code. catch (DataIntegrityViolationException ex) But such a thing not exists. When I apply that code, it says can not find symbol. Which means can not use DataIntegrityViolationException inside catch block. I got solution from here. stackoverflow.com/questions/1988570/…