用tomcat配置的连接池,只能使用十几分钟(这段时间中不断的点击页面,访问数据库),这时重启tomcat又可以用一段时间。我的访问数据库的代码如   回帖一jsp页面的代码如          回帖二 大侠来瞧瞧是哪里错误了?

解决方案 »

  1.   

    package ssh;import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
     import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    public class SqlConn
    {
       private Connection conn = null;
    private Statement  stmt=null;
    private ResultSet  rs=null;

    //注意构造函数不许有返回值,即使void也不行!!!!!!!!!
    public SqlConn() throws SQLException
    {
    //getStatement();
    stmt=getStatement();
    }
    public Statement getStatement() throws SQLException
    {
      
        DataSource ds = null;
        try
        {
        Context ctx = new InitialContext();
        ds = (DataSource) ctx.lookup("java:comp/env/jdbc/sqlserver");
         if (ds != null)
         {
              conn = ds.getConnection();
         }
       
        }catch(Exception e)
        {
         e.printStackTrace();
        }
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_READ_ONLY);
        return stmt;
    } public ResultSet getResultset(String sql) throws SQLException
    {
    //stmt=getStatement();
    rs = stmt.executeQuery(sql);
    return rs;
    } public int executeSql(String sql) throws SQLException
    {
    //stmt=getStatement();
    int rs = stmt.executeUpdate(sql); return rs;
    } public void dbClose()
    {
         try { 
      if (rs != null)        rs.close(); 
                      if (stmt != null)      stmt.close();                     
                      if (conn != null)       conn.close(); 
                        
                 }catch (SQLException e) 
         { 
                        System.out.println(e); 
                 }
    }

    }
      

  2.   

    <%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*,java.io.*" errorPage="" %>
    <%@ page import="ssh.*"%>
    <%
    String name=(String)session.getAttribute("name");
    if(!"123456789".equals(name))
    {
    response.sendRedirect("../error.htm");
    return;
    }
    %>
    <%
    String id=request.getParameter("id");
    String sql_news="delete from cuba where id="+id;
    //out.print(sql_news.length());
    String sql_news_select="select picture from cuba where id="+id;try{
    SqlConn sqlconn=new SqlConn();
    ResultSet rs=sqlconn.getResultset(sql_news_select);if(rs.next())
    {
    String pictures=rs.getString("picture");
    String[] files=pictures.split("[%]");
    String path=request.getRealPath("/");
    for(int i=1;i<files.length;i++)
    {
    File file=new File(path+"cuba\\resource\\"+files[i]);
    file.delete();
    }
    sqlconn.executeSql(sql_news);
    }sqlconn.dbClose();
    response.sendRedirect("opSucc.htm");
    }
    catch(Exception e)
    {
    e.printStackTrace();
    response.sendRedirect("opFail.htm");
    }
    %>
      

  3.   

    报的异常如下:
    org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
    at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:104)
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
    at ssh.SqlConn.getStatement(SqlConn.java:37)
    at ssh.SqlConn.<init>(SqlConn.java:23)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:79)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
    at java.lang.Thread.run(Unknown Source)
    Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
    at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:958)
    at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:96)
    ... 24 more
      

  4.   

    LZ试试C3P0吧1.配置文件:c3p0-config.xml<c3p0-config>
    <default-config>
    <property name="checkoutTimeout">30000</property>
    <property name="idleConnectionTestPeriod">30</property>
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
    <property name="maxStatements">200</property>
    <user-overrides user="test-user">
    <property name="maxPoolSize">10</property>
    <property name="minPoolSize">1</property>
    <property name="maxStatements">0</property>
    </user-overrides>
    </default-config><!-- This app is massive! -->
    <named-config name="fccscom">
    <property name="jdbcUrl">jdbc:jtds:sqlserver://localhost:1433/fs</property> 
    <property name="driverClass">net.sourceforge.jtds.jdbc.Driver</property> 
    <property name="user">sa</property> 
    <property name="password">sunwei</property> 


    <!-- he's important, but there's only one of him -->
    <user-overrides user="master-of-the-universe">
    <property name="acquireIncrement">1</property>
    <property name="initialPoolSize">1</property>
    <property name="minPoolSize">1</property>
    <property name="maxPoolSize">5</property>
    <property name="maxStatementsPerConnection">50</property>
    </user-overrides>

    <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> 
         <property name="acquireIncrement">50</property> 
        
         <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> 
        <property name="acquireRetryAttempts">30</property> 
        
         <!--两次连接中间隔时间,单位毫秒。Default: 1000 --> 
        <property name="acquireRetryDelay">1000</property> 
        
         <!--连接关闭时默认将所有未提交的操作回滚。Default: false --> 
         <property name="autoCommitOnClose">false</property> 
        
         <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效  
           保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试  
           获取连接失败后该数据源将申明已断开并永久关闭。Default: false--> 
         <property name="breakAfterAcquireFailure">false</property> 
        
         <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出  
           SQLException,如设为0则无限期等待。单位毫秒。Default: 0 --> 
         <property name="checkoutTimeout">0</property> 
        
         <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> 
         <property name="idleConnectionTestPeriod">60</property> 
        
         <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> 
         <property name="initialPoolSize">10</property> 
        
         <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> 
         <property name="maxIdleTime">40</property> 
        
         <!--连接池中保留的最大连接数。Default: 15 --> 
         <property name="maxPoolSize">200</property> 
        
         <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements  
          属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。  
           如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0--> 
         <property name="maxStatements">100</property>      <!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能  
           通过多线程实现多个操作同时被执行。Default: 3--> 
         <property name="numHelperThreads">3</property>      <!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:  
           测试的表必须在初始数据源的时候就存在。Default: null--> 
         <property name="preferredTestQuery">select top 1 AREAID from AREA where PASS=1</property> 
        
         <!--用户修改系统配置参数执行前最多等待300秒。Default: 300 --> 
         <property name="propertyCycle">
         300
        </property> 
        
         <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的  
           时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable  
          等方法来提升连接测试的性能。Default: false --> 
         <property name="testConnectionOnCheckout">
         true
         </property> 

        <!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false --> 
         <property name="testConnectionOnCheckin">
         true
         </property> 

    <property name="minPoolSize">
    5
    </property>
    </named-config>
    </c3p0-config> 2.DAO类public final class C3P0Dao implements JavaDao{
    private Connection con  = null;
    private Statement  stmt = null;
    private PreparedStatement pstmt = null;
    private ResultSet  rs   = null;
    private static ComboPooledDataSource cpds = null;
    private HashMap cloummap = null;

    public C3P0Dao(){
    if(cpds==null){
    cpds = new ComboPooledDataSource();
    }
    }

    public C3P0Dao(String type){
    if(cpds==null){
    cpds = new ComboPooledDataSource(type);
    }
    }

    /**
     * SAVE
     * @param SQL
     * @return
     */
    public int save(Object SQL){
    try {
    con = cpds.getConnection();

    stmt = con.createStatement();

    stmt.execute(SQL.toString());

    return 1;
    } catch (Exception e) {
    return 0;
    }finally{
    this.attemptClose(con);
    this.attemptClose(stmt);
    }
    }        ……
    }
      

  5.   

    你试一下 在jsp上 强制 关闭 conn 看看
      

  6.   

    try{
    SqlConn sqlconn=new SqlConn(); 改成SqlConn sqlconn=new SqlConn(); 
    try{
    ..
    }finally{
      sqlconn.dbClose(); 
    }
      

  7.   

    try{
    SqlConn sqlconn=new SqlConn(); 改成SqlConn sqlconn=new SqlConn(); 
    try{
    ..
    }finally{
      sqlconn.dbClose(); 
    }
      

  8.   

    我释放了啊,类中的dbClose()方法就是释放连接的,而且每个页都调用了这个函数
      

  9.   

    上边代码的和我写的不是一样么?(如果数据库访问正常,没有抛出异常)
    try{ 
    SqlConn sqlconn=new SqlConn(); 
    ...
    sqlconn.dbClose(); 
    }catch(Exception e) 

    e.printStackTrace(); 
    }
      

  10.   

    建议数据库的操作不要放在页面里面。可以这样改:page:...
    bo.operate();
    ...bo:
    public  model operate() {
      get db resource;
      try
      process;
      finally
        free db resource;
      end;
    };