简体   繁体   中英

Calling Stored Procedures in Java

I'm using JDBC driver for PostgreSQL and I want to call stored procedures.

Assume I have a method that calls a stored procedure as follows:

public void callProcedure(int someValue)    {

    Connection con = null;
    try {
        con = connectionPool.getConnection();

        CallableStatement st = con.prepareCall("{ call some_procedure(?) }");
        st.setInt(1, someValue);
        st.execute();
        st.close();
    }
    catch (SQLException e)  {
        System.out.println(e.getMessage());
    }
    finally     {
        if (con != null) {
            try { con.close(); } // assure connection "goes" back to the pool
            catch (SQLException e)  { }
        }
    }
}

Now let's assume that this method callProcedure could possibly be called million of times. My questions are:

(1.) Would it be better (performance wise) if I create the connection in the constructor of my class and also prepare_the_Call in the constructor, so something like this:

CallableStatement st;

public Constructor() {
   Connection con = connectionPool.getConnection();
   st = con.prepareCall("{call some_procedure(?)}");
}

and then inside the method do:

   public void callProcedure(int someValue) {
    try {
        st.setInt(1, someValue);
        st.execute();
        st.close();
    }
    catch (SQLException e)  {
        System.out.println(e.getMessage());
    }
    finally     {
        if (con != null) {
            try { con.close(); } // assure connection "goes" back to the pool
            catch (SQLException e)  { }
        }
    }
    }

(2.) Does it make sense to close the connection always after executing a statement? Or should I leave it open? From my understanding, closing it gives the connection back to the connection pool so it could be used by someone else. Is that correct?

  1. Putting that statement in the constructor will not lead to an increase in performance. You are simply creating the Connection at a different point in the object life-cycle.

  2. You are right, closing the Connection will immediately return it to the connection pool, instead of waiting for that to happen automatically. It is best practice to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM