我的Swing应用程序很少抛出异常。我试图捕获完整性约束冲突异常并显示消息“Duplicate ID”。但当发生这种情况时,如果不在这里捕获它:catch(MySQLIntegrityConstraintViolationException ex)它将转到catch(SQLException ex)。我要做的是捕获完整性冲突异常并显示用户友好的消息,而不是来自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);
              }
        }

最佳答案

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

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

Found from here

关于mysql - Java Mysql完整性约束违反异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15894455/

10-09 04:00