在 JAVA 中发现 SQL 错误?

Catching SQL errors in JAVA?

我从我的 Oracle DB 中得到 SQL 结果集 Java 我想知道我是否以及如何可以 record/catch SQL 错误在 Java。所以当我尝试执行一些 SQL:

ResultSet resultSet = connection.executeQuery(query);

我收到类似 ORA-00942: table or view does not exist 的错误。我怎样才能记录下来?

使用 catch 语句存储正确的 SQL 异常,因为 want/need:

try (ResultSet rs = statement.executeQuery(query)) {
    /* retrieve the data */
} catch (SQLException e) {
    /* handle the exception properly */
    storeExceptionSomewhereElse(e);
}

//...

public void storeExceptionSomewhereElse(SQLException e) {
    /*
        Here you can store the exception in database
        or external data source.
    */
}

如果您想要一个更健壮的解决方案并将记录来自 executeQuery 的每个异常,请通过实施所述接口为连接和语句创建包装器 类,然后代理对真实连接对象的调用。更改用于获取连接的逻辑,并将原始连接作为构造函数参数传递。像这样:

public class WrapperConnection implements java.sql.Connection {
    public Connection _realConn;

    public WrapperConnection(Connection realConnection) {
        _realConn = realConnection;
    }

    @Override
    public Statement createStatement() throws SQLException {
        return new WrapperStatement(_realConn.createStatement());
    }

    ...lots of other implmented proxy methods...
}

和语句对象:

public class WrapperStatement implements Statement {

    public Statement _realStmt;

    public WrapperStatement(Statement realStmt) {
        _realStmt = realStmt;
    }

    @Override
    public ResultSet executeQuery(String sql) throws SQLException {
        try {
            return _realStmt.executeQuery(sql);
        } catch(SQLException sqlEx) {
            logSQLException(sqlEx);
            throw sqlEx;
        }
    }

    ...lots of other implemented proxy calls...

}

繁琐的部分是您必须在接口中实现所有其他调用,但它们非常简单,基本上将每个调用代理到传递给构造函数的 "real" 对象;再一次,这将使您有机会记录每种类型的调用(获取准备好的调用等)。您还可以使用它来记录通过 executeQuery() 执行的 SQL,并将其配对除了抛出的异常。

您可以使用 try-catch 来获取错误。然后你可以设置一个记录器来记录异常。

例如:

catch(SqlException e){
     Logger.LogDB("Record1: "+ e);
}