我做了个网站数据库用的是MySQL5,用了c3p0连接池,不是配置在配置文件中的,而是直接写在代码中的,问题是启动Tomcat6之后的一段时间与数据库连接的部分操作就不好使了,表现是页面跳转不到想去的下一个页面,若在这时关掉服务器会瞬间提示页面找不到 (这是正常的啊),我想是和数据库连接这里出了问题(卡在了这里),可能是连接全部被占用完了还是怎么回事儿,我使用的时候都是这么写的Statement st = DBPool.getInstance().getStatement();之后关掉相应的Statement和ResultSet,对于连接什么都没做,我想是不用做的,具体问题在哪知道的指点一下。连接池的全部代码如下:package com.cs.db;import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.beans.PropertyVetoException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;public class DBPool {
private static DBPool dbPool;
private ComboPooledDataSource dataSource; static {
dbPool = new DBPool();
} public DBPool() {
try {
dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/cs?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"); dataSource.setInitialPoolSize(2);
dataSource.setMinPoolSize(2);
dataSource.setMaxPoolSize(50);
dataSource.setMaxStatements(180);
dataSource.setMaxIdleTime(256);
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
} public synchronized final static DBPool getInstance() {
if (dbPool == null) {
dbPool = new DBPool();
}
return dbPool;
} public final Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
} public final Statement getStatement(){
Connection conn = getConnection();
if(conn != null){
try {
return conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}

return null;
}


public final void cleanPool() {
if (dataSource != null) {
try {
DataSources.destroy(dataSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

解决方案 »

  1.   

    你这段代码有很多的问题!比如通过 public final Statement getStatement() 获得的 Statement 对象,那这其中的 Connection 不需要关闭么?再比如 public final void cleanPool() 这句是干嘛用的?清除连接池?为什么要清除?再比如 public DBPool() 可以改为私有构造,方法上的 final 就可以全部去掉。再比如 DBPool 构造中写死在代码里的连接参数最好能写到配置文件中去,这样可以保证以后 JDBC 连接参数更改后不需要改动代码。
      

  2.   

    我做了个网站数据库用的是MySQL5,用了c3p0连接池,不是配置在配置文件中的,而是直接写在代码中的,问题是启动Tomcat6之后的一段时间与数据库连接的部分操作就不好使了,表现是页面跳转不到想去的下一个页面,若在这时关掉服务器会瞬间提示页面找不到 (这是正常的啊),我想是和数据库连接这里出了问题(卡在了这里),可能是连接全部被占用完了还是怎么回事儿,我使用的时候都是这么写的 Statement st = DBPool.getInstance().getStatement();之后关掉相应的Statement和ResultSet,对于连接什么都没做,我想是不用做的,具体问题在哪知道的指点一下。------------------------------------------------
    我不知道你为什么会有这样的想法?
      

  3.   

    我名表过来是怎么回事儿了,应该是通过c3p0连接池得到的Connection重写了close()方法,用完Connection要调用close()方法,这个方法把链接换给了连接池,我想是这个样子的。连接池怎么写到配置文件中我还不会,告诉我一下。    还有连接池会不会有连接超时关闭的情况