【问题标题】:Catching SQL errors in JAVA?在 JAVA 中捕获 SQL 错误?
【发布时间】:2015-08-26 15:58:25
【问题描述】:

我从Oracle DB 获得Java 中的SQL 结果集,我想知道是否以及如何记录/捕获Java 中的SQL 错误。所以当我尝试执行一些SQL:

ResultSet resultSet = connection.executeQuery(query);

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

【问题讨论】:

    标签: java sql oracle try-catch


    【解决方案1】:

    使用catch 语句根据需要/需要存储适当的 SQL 异常:

    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.
        */
    }
    

    【讨论】:

      【解决方案2】:

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

      例如:

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

      【讨论】:

        【解决方案3】:

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

        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...
        }
        

        还有 Statement 对象:

        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...
        
        }
        

        麻烦的是你必须在接口中实现所有其他调用,但它们非常简单,基本上将每个调用代理到传递给构造函数的“真实”对象;话又说回来,这将使您有机会记录每种类型的调用(获取准备调用等)。您还可以使用它来记录通过 executeQuery() 执行的 SQL,并将其与异常配对被抛出。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-16
          • 2013-02-23
          • 1970-01-01
          • 1970-01-01
          • 2011-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多