捕获IntegrityConstraintViolationException错误

时间:2014-08-11 16:26:38

标签: java mysql swing validation

我从控制台收到此错误消息

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry   'PROTOCOL AND INTERNATIONAL RELATIONS-S9614275G' for key 'uniqueindex'
执行这些代码时

public boolean createAssignRequest(AssignmentRequests assignReq) {

    int id = assignReq.getReqId();
    String dutyName = assignReq.getDutyName();
    String volNric = assignReq.getVolNric();

    boolean success = false;
    DBController db = new DBController();
    String dbQuery = "";
    Connection conn = null;


    db.getConnection();

    dbQuery = "INSERT into assignrequests (dutyName, volNric)"
            + " VALUES ('" + dutyName + "','" + volNric + "')";

    if (db.updateRequest(dbQuery) == 1) {
        success = true;
    }
    db.terminate();

    return success;

}

如何捕获错误并显示JOptionPane以显示错误消息?

我的updateRequest方法代码:

    public int updateRequest(String dbQuery) {
    int count = 0;
    System.out.println("DB Query: " + dbQuery);
    try {
        // create a statement object
        Statement stmt = con.createStatement();
        // execute an SQL query and get the result
        count = stmt.executeUpdate(dbQuery);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return count;
}

1 个答案:

答案 0 :(得分:0)

试试这个:

public boolean createAssignRequest(AssignmentRequests assignReq) {

    int id = assignReq.getReqId();
    String dutyName = assignReq.getDutyName();
    String volNric = assignReq.getVolNric();

    boolean success = false;
    DBController db = new DBController();
    String dbQuery = "";
    Connection conn = null;

    ResultSet resultSet = null;

    db.getConnection();

    dbQuery = "INSERT into assignrequests (dutyName, volNric)"
            + " VALUES ('" + dutyName + "','" + volNric + "')";


    resultSet = db.updateRequest(dbQuery) == 1;

    try {
        if (rs.next()) {
            success = true;
        }
    }
    catch (Exception e)
    {
        // Error handling here.
    }

    db.terminate();

    return success;

}