The answer to your question 'why the first causes a memory leak when reusing the connection Object?'
Yes, you are reusing the connection object but you are creating a new JdbcRowSet
object in every iteration and you don't close it which leads to memory leak. The jdbcRS = null;
doesn't close the resource.
The answer to your question 'why can I not close the ResultSet in the first snippset but in the second?'
In your first code snippet, when you close the JdbcRowSet
object jdbcRS
using the close method , jdbcRS.close();
you close the connection as well. So the second iteration will throw a NullPointerException because at jdbcRS = new JdbcRowSetImpl(connection);
the connection
is already closed.
The second code snippet works fine because you create a new connection in every iteration
in the getConnection
method.
The best would be if you used CachedRowSet
for closing the resource after every iteration automatically:
package databases;
import java.sql.SQLException;
import javax.sql.rowset.*;
public class CachedRowSet_Usage {
public static void main(String[] args) {
String username = "username";
String password = "password";
String url = "jdbc:mysql://localhost:3306/your_database_name";
try{
CachedRowSet rs = RowSetProvider.newFactory().createCachedRowSet();
//JdbcRowSet rs = RowSetProvider.newFactory().createJdbcRowSet();
rs.setUrl(url);
rs.setUsername(username);
rs.setPassword(password);
for(int i=0;i<150;i++){
System.out.println(i);
rs.setCommand("Select * from your_table");
rs.execute();
//rs.close(); <-- no use, rs closes automatically
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}