2015-01-12 65 views
0

這是我的連接類。我需要返回結果集到特定的類。但我發現resultset在該類中關閉。我在我的連接中使用連接池。 我想創建一個通用的連接類,管理我的應用程序中的數據庫的所有操作。如何從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

好舒利已經回答了您的問題。在返回之前,您已經關閉了ResultSet。

但是,要添加到您試圖實現的目標。

1)圍繞你的return dataSource.getConnection在try catch。

2)創建單獨的query功能和connection close功能類似下面

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

} 

當你的代碼擴展這會給你更多的flexibilty。