gpt4 book ai didi

java - 捕获 IntegrityConstraintViolationException 错误

转载 作者:行者123 更新时间:2023-11-29 23:57:19 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com