Sallyerik
Sallyerik

Reputation: 519

error " Operation not allowed after ResultSet closed" on Mysql connection closing

I'm calling to this class from other part of my appiclation and it's working fine. However I would like to close every single mysql connection which has been open.

This is my class to connect to my database:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;





public class BACENGQueryDatabases {
    public String Query;


    public BACENGQueryDatabases(String Query){
        this.Query = Query;
    }

    public ResultSet LoadQuery() throws Exception{  

    // Accessing Driver From Jar File
    Class.forName("com.mysql.jdbc.Driver");

//Get credentials from Property file
BACENGPropertiesFile user = new BACENGPropertiesFile("user.cred");
BACENGPropertiesFile passwd = new BACENGPropertiesFile("passwd.cred");
BACENGPropertiesFile database = new BACENGPropertiesFile("database.system");
BACENGPropertiesFile DBServer = new BACENGPropertiesFile("DBServer.system");
BACENGPropertiesFile DBPort = new BACENGPropertiesFile("DBPort.system");

Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;


//DB Connection

          con = DriverManager.getConnection("jdbc:mysql://"+DBServer.properties()+":"+DBPort.properties()+"/"+database.properties()+"",""+user.properties()+"",""+passwd.properties()+"");       
    //DB Connection
           String sql =Query; 
           pst = con.prepareStatement(sql);
    //System.out.println(sql); //Just to test

          rs=pst.executeQuery();

     con.close();
    return rs;


    }

}

The problem is happening when I try to close the connection trought:

con.close();

Then, the output is:

"Operation not allowed after ResultSet closed"

Upvotes: 0

Views: 498

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 108941

When you close a Connection like you do in your code, then any dependent objects like the ResultSet created from that connection are closed as well. You either need to keep your connection open as long as you need your result set, use a CachedRowSet or transfer the contents of the result set to something else before returning it.

Upvotes: 4

Related Questions