Java Mysql完整性约束违例异常

时间:2013-04-09 06:07:10

标签: mysql swing exception constraints unique-constraint

我的Swing应用程序抛出了一些例外。我试图捕获Integrity Constraint Violation Exception并显示消息“Duplicate ID”。但是当发生这种情况时,没有在这里捕获它:catch(MySQLIntegrityConstraintViolationException ex)它会捕获(SQLException ex)。我想要做的是,捕获Integrity Violation异常并显示用户友好消息,而不是来自ex.getMessage()的技术消息。我该怎么做呢?

              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);
              }
        }

3 个答案:

答案 0 :(得分:2)

为了捕获特定的SQLException,需要使用getSQLState()方法与SQl State进行比较。例如:SQl State 23用于数据完整性违规。

 catch (SQLException ex) {
                    if (ex.getSQLState().startsWith("23")) {
                          JOptionPane.showMessageDialog(null, "Duplicate");
                    } 
              }

Found from here

答案 1 :(得分:1)

你不能使用

MySQLIntegrityConstraintViolationException  directly.

因为在具有该名称的java中没有可用的异常。

试试这个

try {

}
catch (DataIntegrityViolationException ex) {
    .....
}

然后使用ex获取错误代码然后比较

答案 2 :(得分:1)

对于那些稍后检查, 您可以选择将实例类型检查为:

try {
...
} catch (Exception e) {

    if (e instanceof SQLIntegrityConstraintViolationException) {
          // duplicate record or alike problem
    }
}