jdbc中使用c3p0来获取连接

本文介绍了一个使用ComboPooledDataSource配置数据库连接池的例子。通过设置JDBC驱动、URL、用户名及密码等属性,实现了连接池的最大和最小连接数限制,并禁用了可能导致死锁的maxStatements属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值