java - 捕获 IntegrityConstraintViolationException 错误

标签 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;
}

最佳答案

试试这个:

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;

}

关于java - 捕获 IntegrityConstraintViolationException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25247974/

相关文章:

java - 当 JTextArea 超过一定数量的行时启用滚动条

Java - 是否可以在 GridLayout 的同一侧放置两个组件?

java - 如何使我的 JComponent 符合 JFrame.pack 和布局管理器?

java - Java 的 lorem ipsum 生成器,在 Maven Central 中可用?

java - 如何使用限制为 n 的递归 java 打印奇数

php - MySQL 左连接查询具有相同值的问题

php - 如何显示MySQL表的平均值

java - Hibernate 4.3.6 和 Glassfish 4.0 JPA 2.1 对象不是声明类的实例

mysql - 配置 Rails 应用程序以使用现有数据库

java - JTextField 上的圆角并使其通过不同的 PLAF 保持一致