更新时间:2023-10-10 08:35:28
我有一个建议,我在我的申请中使用。我们可以从 PersistenceException
中检索 SQLException
。之后,尝试为 SQLException
获取 sql错误代码
。如果你的要求是获得 sql错误代码
,你可以按照我的例子;
I have a suggestion which is I use in my application. We can retrieve the SQLException
from PersistenceException
. After that, try to get sql error code
for SQLException
. If your requirement is to get the sql error code
, your can follow my example;
public void insert(Group group) throws DAOException {
try {
//your operation
em.flush();
logger.debug("insert() method has been successfully finisehd.");
} catch (PersistenceException pe) {
String sqlErroCode = getErrorCode(pe);
// do your operation based on sql errocode
}
}
protected String getErrorCode(RuntimeException e) {
Throwable throwable = e;
while (throwable != null && !(throwable instanceof SQLException)) {
throwable = throwable.getCause();
}
if (throwable instanceof SQLException) {
Properties properties = --> load sql error code form configuration file.
SQLException sqlex = (SQLException) throwable;
String errorCode = properties.getProperty(sqlex.getErrorCode() + "");
return errorCode;
}
return "NONE";
}
mysql的示例错误代码配置
Example error code configuration of mysql
mysql_error_code.properties
mysql_error_code.properties
#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED