jdbc中使用c3p0来获取连接

static{

ComboPooledDataSource dsWebgame = new ComboPooledDataSource();

try {
   dsWebgame.setDriverClass("com.microsoft.jdbc.sqlserver.SQLServerDriver");
  } catch (PropertyVetoException e) {
   e.printStackTrace();
  }  // 参数由 Config 类根据配置文件读取   
        // 设置JDBC的URL   
  String url = "jdbc:sqlserver://"+host+":1433;DatabaseName=JY_DB;SelectMethod=cursor";
  dsWebgame.setJdbcUrl(url);   
      // 设置数据库的登录用户名   
  dsWebgame.setUser(name);   
      // 设置数据库的登录用户密码   
  dsWebgame.setPassword(psw);   
      // 设置连接池的最大连接数   
  dsWebgame.setMaxPoolSize(35);   
      // 设置连接池的最小连接数   
  dsWebgame.setMinPoolSize(20); 

  dsWebgame.setMaxStatements(0);//有时候会产生死锁,将maxStatements设置为0

}

 

 

/**
  * 获取数据库连接
  * @return
  */
 public static synchronized Connection getConnection(){
  if(null ==connection){
   return newConnection();
  }else{
   return connection;
  }
 }

 

/**
  * 创建数据库连接
  * @return
  */
 private static Connection newConnection() {
  try {
   return dsWebgame.getConnection();
  } catch (SQLException e) {
   e.printStackTrace();
   return null;
  }
 }

posted @ 2010-04-17 12:21  心梦帆影  阅读(1498)  评论(0编辑  收藏  举报