避免在servlet中关闭自动jdbc连接

时间:2014-05-18 17:40:48

标签: java mysql jdbc

我在Jetty 9服务器上部署了一个servlet,它使用http://dev.mysql.com/downloads/connector/j/5.0.html中的Connector / J JDBC驱动程序连接到MySQL 5.6.17服务器。

这个特殊的servlet在for循环中触发一个SQL语句,迭代大约10次。我必须包括

DriverManager.getConnection(DB_URL, USER, PASSWORD);

在此循环中行,因为在循环的每次迭代中执行SQL语句后,连接会自动关闭。

有没有办法保持连接打开,这样getConnection()只需要在循环开始之前执行一次,然后我可以在finally块中手动关闭它。

我在这个特定问题上找到了很多帖子,但都将连接池概念称为解决方案。但我只是想避免在每次查询执行后自动关闭连接。这不应该是一个简单的参数吗?我现在没有遇到任何特定的性能问题,但它似乎浪费了处理器和网络周期。

Servlet代码:

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);
    }

1 个答案:

答案 0 :(得分:0)

问题是您正在关闭for循环内的连接。只需移动两个语句:连接打开和连接关闭,在循环外。

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) {
}