Search code examples
javajdbcconnection-pooling

Java JDBC Connection Pooling (How to check)?


First of all, I'm new to Java/JSP/Eclipse. However, I've many many years of .Net experience. I have just learned in Java how to make a connection to MS SQL Server using the javax.sql.DataSource (so that I don't need to key in the userid/password).

Right now, I've created a class to handle DB query, and in that class, I have a function that I can just call to return a RowSet.

    import javax.naming.Context;
    import javax.naming.InitialContext;
    import java.sql.Connection;

    import javax.sql.DataSource;
    import javax.sql.rowset.JdbcRowSet;
    import com.sun.rowset.JdbcRowSetImpl;

    public abstract class ClsDBAccessBASE {
        public boolean prbAutoCommit = true;
        public String prsDataSourceName = "";

            public ClsDBAccessBASE( String pvsDataSourceName ) {
                    prsDataSourceName = pvsDataSourceName;
            }
            public JdbcRowSet fnorsSQLText( String pvsSQLText ) {
                JdbcRowSet voRS = null;

                try {
                    Context voContext = new InitialContext();
                    DataSource voDS = (DataSource)voContext.lookup(prsDataSourceName);
                    Connection voConn = (Connection)voDS.getConnection();
                    voRS = new JdbcRowSetImpl((voConn.createStatement()).executeQuery(pvsSQLText));
                } catch (Exception e) {e.printStackTrace();}

                return voRS;
            }
        }
    }

My objective is to ensure that I am using Connection Pooling. I understand that the JdbcRowSet implements that automatically? However, the problem (I think) is that I am casting the (voConn.createStatement()).executeQuery(pvsSQLText) from a ResultSet to a JdbcRowSet. Would this mean that the underlying connection used is still ResultSet? and not RowSet? Is there a way for me to check that I am indeed using Connection Pooling?

I'm sorry, if my question sounds silly. I am very new to Java development & Eclipse. Please bear with me and I will appreciate any guidance you can provide me.

I am using: sqljdbc4.jar from Microsoft (which seems to give me error whenever I call the JdbcRowSet.execute() function and/or .next() function. Something about NullReference. But that's another problem.


Solution

  • Yes, if you use container DataSource, it do connection pooling for you.

    Connection pooling not depend of RowSet implementation, and rowset should be closed after use. I suggest to read it immediatly into array of plain object and close. And don't use JdbcRowSetImpl, RowSet will be enough.

    EDIT: i forget to answer your question: Check how many connection you have in pool, than in loop call getConnection and execute select, and do not close ResultSet. You get error when you reach count open connection == configured max open connection in connection pool.