2015-01-12 2 views
0

이것은 내 connetion 클래스입니다. 결과 집합을 특정 클래스로 반환해야합니다. 하지만 그 결과 클래스는 그 클래스에서 닫힌 것으로 나타났습니다. 내 연결에 connectio 풀링을 사용합니다. 내 응용 프로그램의 데이터베이스에 대한 모든 작업을 관리하는 일반 연결 클래스를 만들고 싶습니다.jdbc 연결의 메서드에서 결과 집합을 반환하는 방법

import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 

import javax.naming.Context; 
import javax.naming.InitialContext; 
import javax.naming.NamingException; 
import javax.sql.DataSource; 

public class OpenTestConnection { 
    private DataSource dataSource=null; 
    private Connection connection=null; 
    private Statement statement=null; 

    public OpenTestConnection() 
    { 
     System.out.println("come in Openconnection...."); 
     try { 
      // Get DataSource 
      Context initContext = new InitialContext(); 
      Context envContext = (Context)initContext.lookup("java:/comp/env"); 
      dataSource = (DataSource)envContext.lookup("jdbc/ietddb"); 
     } catch (NamingException e) { 
      e.printStackTrace(); 
     } 
    } 
    private Connection getConnection() throws SQLException { 
     return dataSource.getConnection(); 
    } 
    public ResultSet selectfromtable(String sql) 
    { 
     System.out.println("come here...."); 
     ResultSet resultSet = null; 
     try { 
      connection = getConnection(); 
      statement = connection.createStatement(); 
      resultSet = statement.executeQuery(sql); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     }finally { 
      try { if(null!=resultSet)resultSet.close();} catch (SQLException e) 
      {e.printStackTrace();} 
      try { if(null!=statement)statement.close();} catch (SQLException e) 
      {e.printStackTrace();} 
      try { if(null!=connection)connection.close();} catch (SQLException e) 
      {e.printStackTrace();} 
     } 
     return resultSet; 
    } 
} 
+1

반환하기 전에'resultSet.close()'를 호출하고 있습니다. –

답변

0

음 Shree가 귀하의 문제에 답변했습니다. ResultSet을 리턴하기 전에 닫았습니다.

그러나 달성하려는 대상에 추가하십시오.

1) 귀하의 return dataSource.getConnection을 try catch에서 포위하십시오.

2) 별도의 query 기능과 코드가 확장 될 때 이것은 당신에게 더 많은 유연성을 모두를 줄 것이다

protected Connection connection = null; 
protected Statement statement = null; 
protected PreparedStatement prepared = null; 

// executeQuery 
protected ResultSet execute(String sql) throws SQLException { 
    connection = getConnection(); 
    statement = connection.createStatement(); 
    return statement.executeQuery(sql); 
} 

//now have a close function 
protected void commitAndClose() { 
    if (connection != null) { 
     try { 
      connection.commit(); 
     } catch (SQLException ex) { 
      // your code for handling ex 
     } finally { 
      try { 
       resultSet.close(); //do not know why you are closing resultset 
       statement.close(); 
       connection.close(); 
      } catch (SQLException ex) { 
       LOGGER.log(Level.SEVERE, null, ex); 
      } 
      connection = null; 
     } 
    } 

} 

아래 같은 connection close 함수를 만듭니다.

관련 문제