为了扩展已接受的答案,我将提供从 SQL 查询中检索错误位置所需的 JDBC 代码。
PL/SQL:
此 PL/SQL 块接受 sql 查询文本并返回错误位置:
DECLARE
c INTEGER := DBMS_SQL.open_cursor();
errorpos integer := -1;
BEGIN
BEGIN
DBMS_SQL.parse(c, :sqltext, DBMS_SQL.native);
EXCEPTION
WHEN OTHERS THEN
errorpos := DBMS_SQL.LAST_ERROR_POSITION();
END;
:errorpos := errorpos;
DBMS_SQL.close_cursor(c);
END;
它接受两个参数sqltext
和errorpos
.
爪哇:
在 Java 方面,我们需要从上面调用 PL/SQL 代码并检索错误位置。这是一种方法:
private int retrieveErrorPosition(Connection connection, String query) {
CallableStatement callStatement = null;
try {
callStatement = connection.prepareCall(LAST_ERROR_POSITION_QUERY);
callStatement.setString(1, query);
callStatement.registerOutParameter(2, OracleTypes.INTEGER);
callStatement.execute();
return callStatement.getInt(2);
} catch (SQLException ex) {
log.log(Level.SEVERE, "", ex);
} finally {
if (callStatement != null) {
try {
callStatement.close();
} catch (SQLException sqle) {
}
}
}
return -1;
}
用法:
现在,如果查询字符串执行异常,我们可以提取错误位置:
String query;
Connection connection;
try {
//normal query execution
} catch (SQLException ex) {
int sqlErrorPosition = retrieveErrorPosition(connection, query);
//exception handling
}