0

我里面有一些 OAF 代码,我正在启动 sql 连接,但是当我试图关闭它时,它会引发 sql 异常。这是代码。

    try
    {
        conn = 
        (OracleConnection)oadbtransactionimpl.getJdbcConnection();
        String queryForEmpty = 
            "select ... query here"; 
        projectDetailsStatment = 
                conn.prepareStatement(queryForEmpty);
        projectDetailsStatment.setString(1,sprojectid);
        ResultSet rs = projectDetailsStatment.executeQuery();

    }
    catch(SQLException e)
   {
       String sqlErrMsg = e.getMessage();
       throw new OAException((new StringBuilder()).append("handle exception here:").append(sqlErrMsg).toString(), (byte)0);
   }
   finally
   {
      conn.close(); // throws exception here
   }
4

2 回答 2

0

尝试用 try 和 catch 子句括起结束代码

    try
    {
        conn = 
        (OracleConnection)oadbtransactionimpl.getJdbcConnection();
        String queryForEmpty = 
            "select ... query here"; 
        projectDetailsStatment = 
                conn.prepareStatement(queryForEmpty);
        projectDetailsStatment.setString(1,sprojectid);
        ResultSet rs = projectDetailsStatment.executeQuery();

    }
    catch(SQLException e)
   {
       String sqlErrMsg = e.getMessage();
       throw new OAException((new StringBuilder()).append("Exception in Finding Project Type:").append(sqlErrMsg).toString(), (byte)0);
   }
   finally
   {
      try{
      conn.close(); // throws exception here
      }
        catch(SQLException e)
      {
        //your code here
      }
   }
于 2017-10-31T10:57:31.903 回答
0

任何 JDBC 操作的基本方案都非常简单:

  1. 获取连接。
  2. 创建一个声明。
  3. 执行该语句并获得一个 ResultSet。

  4. 处理结果集。

  5. 关闭所有内容:ResultSet、Statement 和 Connection。

糟糕的解决方案

public void handleJDBC()  {
    try {
        DataSource dataSource = getDataSource();
        Connection connection = dataSource.getConnection();
        operation(connection)
        connection.close();
    } catch (SQLException e) {
        //do something here
    }
}

良好做法

finally {
        if (connection != null) {
            try {
            connection.close();
        } catch (SQLException e) {
            if (exception != null) {
                exception = new DoubleException(exception, e);
            } else {
                exception = e;
            }
        }
        }
    }
    if (exception != null) {
        throw exception;
    }
于 2017-10-31T11:11:56.507 回答