8

如何获取查询中错误的位置?

我需要在导致错误的查询字符串中获取位置,就像sqlplus它一样:

SQL> insert into tbl (data) values('12345')
  2  /
insert into tbl (data) values('12345')
                 *
ERROR at line 1:
ORA-12899: value too large for column "schmnm"."tbl"."data" (actual: 5,
maximum: 3)

我怎样才能做到这一点?

4

3 回答 3

5

在我几乎失去希望的一些杂乱无章之后,我发现(感谢 Google 中的正确搜索字符串)以下链接:https ://forums.oracle.com/thread/1000551

SQL> DECLARE
  2     c   INTEGER := DBMS_SQL.open_cursor ();
  3  BEGIN
  4     DBMS_SQL.parse (c, 'select * form dual', DBMS_SQL.native);
  5
  6     DBMS_SQL.close_cursor (c);
  7  EXCEPTION
  8     WHEN OTHERS THEN
  9        DBMS_OUTPUT.put_line ('Last Error: ' || DBMS_SQL.LAST_ERROR_POSITION ());
 10        DBMS_SQL.close_cursor (c);
 11        RAISE;
 12  END;
 13  /
Last Error: 9
DECLARE
*
ERROR at line 1:
ORA-00923: FROM keyword not found where expected
ORA-06512: at line 11
于 2013-07-16T17:02:10.143 回答
2

为了扩展已接受的答案,我将提供从 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;

它接受两个参数sqltexterrorpos.

爪哇:

在 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
}
于 2015-10-02T11:05:12.640 回答
1

SQLException具有保存 SQL 错误号(如 中ORA-12899)和类似于您所看到的消息的附加字段value too large for column "schmnm"."tbl"."data" (actual: 5, maximum: 3)

如果要真正查明 SQL 语句中的错误,则必须解析字符串。

请参阅:http ://docs.oracle.com/javase/6/docs/api/java/sql/SQLException.html

阅读异常中的errorCodeSQLState属性。

于 2013-07-08T16:59:29.427 回答