mysql连接池的使用工具类代码示例

mysql连接池代码工具示例(scala):

import java.sql.{Connection,PreparedStatement,ResultSet}
import org.apache.commons.dbcp.BasicDataSource

object ConnectPoolUtil{
    private var bs:BasicDataSource = null          

 /**
 *创建数据源
 */
 def getDataSource():BasicDataSource = {
   if (bs = null){
       bs = new BasicDataSource()
       bs.setDriverClassName("com.mysql.jdbc.Driver")
       bs.setUrl("jdbc:mysql://localhost:3306/${db_name}")
       bs.setUsername("root")
       bs.setPassword("123456")
       bs.setMaxActive(200) //设置最大的并发数
       bs.setInitialSize(30) //数据库初始化时,创建的连接个数
       bs.setMinIdle(50) //最小空闲连接数
       bs.setMaxIdle(200) //数据库最大连接数
       bs.setMaxWait(1000)
       bs.setMinEvictableIdleTimeMillis(60 * 1000) //空闲连接60秒之后释放
       bs.setTimeBetweenEvictionRunsMills(5 * 60 * 1000) //5分钟检测一次是否有进程死掉
    }  
    bs
 }

 /**
 *释放数据源
 */
 def shutDownDataSource(){
    if (bs != null) {
        bs.close()
    }  
 }

 /**
 *获取数据库的连接
 */
 def getConnection():Connection = {
     val conn :Connection = null
     try{
          if (bs != null){
             conn = bs.getConnection()
          }else{
              conn = getDataSource().getConnection()
          }
      }catch {
           case e:Exception => println(e.getMessage)
     }
     conn
 }

 /**
 *关闭连接
 */
 def closeConn(rs:ResultSet,ps:PreparedStatement,conn:Connection){
       if (rs != null)
          rs.close()
       if (ps != null)
          ps.close()
       if (conn != null)
          conn.close()
 }
}

  

 

转载于:https://www.cnblogs.com/Gxiaobai/p/9716765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值