简体   繁体   中英

Avoid automatic jdbc connection close in servlet

I have a servlet deployed on a Jetty 9 server that connects to a MySQL 5.6.17 server using the Connector/J JDBC driver from http://dev.mysql.com/downloads/connector/j/5.0.html .

This particular servlet fires a SQL statement inside a for loop that iterates around 10 times. I have to include the

DriverManager.getConnection(DB_URL, USER, PASSWORD);

line within this loop because the connection closes automatically after the SQL statement has been executed in every iteration of the loop.

Is there a way to keep the connection open, so that getConnection() need be executed only once before the loop starts and then i can manually close it in the finally block.

I have found many posts on this particular issue, but all refer to the connection pooling concept as the solution. But i am just interested in avoiding the connection being closed automatically after each query execution. Shouldn't this be a simple parameter? I am not facing any particular performance problem right now, but it just seems to be a waste of processor and network cycles.

Servlet Code :

public class CheckPhoneNumberRegistrationServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException {

    System.err.println("started CheckPhoneNumberRegistrationServlet");


    // define database connection details
    final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    final String DB_URL = DatabaseParameters.SlappDbURL;
    final String USER = DatabaseParameters.DbServer_Username;
    final String PASSWORD = DatabaseParameters.DbServer_Password;
    PreparedStatement prpd_stmt = null;
    Connection conn = null;
    ResultSet rs = null;
    int resultValue;

    // open a connection
    /*try {
        conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
    } catch (SQLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }*/

    JsonParser jsparser;
    JsonElement jselement;
    JsonArray jsrequestarray;
    JsonArray jsresponsearray = new JsonArray();
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        jsparser = new JsonParser();
        jselement = (JsonElement) jsparser.parse(jb.toString());
        jsrequestarray = jselement.getAsJsonArray();



        for (int i = 0; i < jsrequestarray.size(); i++) {
            // System.err.println("i : " + i +
            // jsrequestarray.get(i).toString());

            try {

                conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);

                prpd_stmt = conn
                        .prepareStatement("select slappdb.isPhoneNumberRegistered(?)");

                prpd_stmt.setString(1, jsrequestarray.get(i).toString()
                        .replace("\"", ""));

                rs = prpd_stmt.executeQuery();
                if (rs.first()) {
                    //System.err.println("result sert from sql server : " + rs.getString(1));
                    //slappdb.isPhoneNumberRegistered() actually returns Boolean
                    //But converting the result value to int here as there is no appropriate into to Boolean conversion function available.
                    resultValue = Integer.parseInt(rs.getString(1));
                    if(resultValue == 1)
                        jsresponsearray.add(jsparser.parse("Y"));
                    else if(resultValue == 0)
                        jsresponsearray.add(jsparser.parse("N"));
                    else throw new SQLException("The value returned from the MySQL Server for slappdb.isPhoneNumberRegistered(" + jsrequestarray.get(i).toString().replace("\"", "") + ") was unexpected : " + rs.getString(1) + ".\n");
                    // System.err.println("y");
                }

                else throw new SQLException("Unexpected empty result set returned from the MySQL Server for slappdb.isPhoneNumberRegistered(" + jsrequestarray.get(i).toString().replace("\"", "") + ").\n");

            } catch (SQLException e) {

                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (prpd_stmt != null)
                        prpd_stmt.close();
                } catch (SQLException e1) {
                }
                try {
                    if (conn != null)
                        conn.close();
                } catch (SQLException e1) {
                }
            }
        }

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/plain");
        // resp.setContentLength(1024);
        resp.getWriter().write(jsresponsearray.toString());
        System.err.println(jsresponsearray.toString());

    } catch (Exception e) {
        // crash and burn
        System.err.println(e);
    }

The problem is that you're closing the connection inside the for loop. Just move both statements: connection opening and connection close, outside the loop.

conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
for (int i = 0; i < jsrequestarray.size(); i++) {
    try {
        //current code...
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (prpd_stmt != null)
                prpd_stmt.close();
        } catch (SQLException e1) {
        }
    }
}
try {
    if (conn != null)
        conn.close();
} catch (SQLException e1) {
}

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