2

我正在jsp中执行连接池操作。我在名为MCE_Server.java的特定类中创建了一个静态函数,并包含以下内容

 public static void makeConnectionPool()
 {
    try
    {
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/mce_db");
        cpds.setUser("root");
        cpds.setPassword("xxxxxx");
        cpds.setMaxPoolSize(100);
        cpds.setMinPoolSize(10);
        cpds.setAcquireIncrement(20);
    } 
    catch (PropertyVetoException ex) 
    {

        Logger.getLogger(MCE_Server.class.getName()).log(Level.SEVERE, null, ex);
    }

 }

从jsp页面调用以下静态函数

http://................/dbActivatePage.jsp

我在哪里包含了这个功能

      <%@page import="xxxxx.MCE_Server"%>
      <html>
      .
      .
      .
      <body>
      <%
              MCE_Server.makeConnectionPool();
      %>
      .
      .
      .
      </body>
      </html>

我计划根据MCE_Server.java中包含的静态函数获取所需的连接,如下所示:

       public static Connection getConnectionfromPool() throws SQLException
       {
             return cpds.getConnection();
       }

即每当我需要连接时。我将包括MCE_Server.getConnectionfromPool().

现在我遇到的问题是我收到一个错误

java.sql.SQLException: Connections could not be acquired from the underlying database!

为什么我得到这个......??

在进一步的试验和错误方法中......我发现代码下面的语句 cpds = new ComboPooledDataSource();正在执行。

那么,这里可能有什么问题。我的方法正确吗?

4

2 回答 2

3

这不是一个好方法。每次客户端访问您的页面时,JSP 的 <% ... %> 中的内容都会被执行。每个 Web 应用程序只能创建一次连接池,而不是每个用户请求一次!

我最喜欢在 web 应用程序中设置连接池的方法是设置一个 ServletContextListener,它在 contextInitialized(ServletContextEvent sce) 中创建池,并将其绑定到应用程序范围内的名称(即它设置 ServletContext 属性) . 池应该在 ServletContextListener 的 contextDestroyed 方法中关闭()。

如果这看起来工作量太大,只需将您的 makeConnectionPool() 更改为私有方法并仅从静态初始化程序块内部调用它。摆脱 <% MCE_Server.makeConnectionPool(); %> 完全。那么 makeConnectionPool() 将只被调用一次,当 MCE_Server 类被加载时。但是由于您从不破坏池,如果您卸载并热重新部署应用程序(即您修改并重新加载war 文件而不退出Servlet 容器的JVM),您会发现线程和其他资源的泄漏。

于 2013-02-06T10:43:04.110 回答
1

看看你显示的错误。

java.sql.SQLException: Connections could not be acquired from the underlying database!.

尽管我同意 Waldman 使用 ServletContextListener 的想法,但您的 c3p0 配置似乎是正确的。在您的情况下,我坚信问题与 mysql 类路径有关。请检查您是否正确包含了 mysql 连接器。

于 2013-02-11T08:43:07.997 回答