Druid 连接MySql

Druid 配置文件详解:

#驱动加载
driverClassName=com.mysql.jdbc.Driver
#注册驱动
url=jdbc:mysql://127.0.0.1:3306/student?characterEncoding=utf-8
#连接数据库的用户名
username=root
#连接数据库的密码
password=password
#属性类型的字符串,通过别名的方式配置扩展插件, 监控统计用的stat 日志用log4j 防御sql注入:wall
filters=stat
#初始化时池中建立的物理连接个数。
initialSize=2
#最大的可活跃的连接池数量
maxActive=300
#获取连接时最大等待时间,单位毫秒,超过连接就会失效。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
maxWait=60000
#连接回收器的运行周期时间,时间到了清理池中空闲的连接,testWhileIdle根据这个判断
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql,要求是一个查询语句。
validationQuery=SELECT 1
#建议配置为true,不影响性能,并且保证安全性。 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis, 执行validationQuery检测连接是否有效。
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。设置为false
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能,设置为flase
testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。
poolPreparedStatements=false
#池中能够缓冲的preparedStatements语句数量
maxPoolPreparedStatementPerConnectionSize=200

连接代码:

package com.jdbc.utils;
 
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
 
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
 
public class JDBCDruid {
     
    private static Properties properties;
    private static  JDBCDruid druid;
    private static DruidDataSource ds;
     
     
    static {
        properties=new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 创建单列模式
     * @return JDBCDruid实例
     */
    public static synchronized JDBCDruid getInstance() {
        if(druid==null) {
            druid=new JDBCDruid();
            return druid;
        }
        return druid;
    }
     
    private JDBCDruid() {
 
        ds=new DruidDataSource();
        ds.setDriverClassName(properties.getProperty("driverClassName"));
        ds.setUrl(properties.getProperty("url"));
        ds.setUsername(properties.getProperty("username"));
        ds.setPassword(properties.getProperty("password"));
        ds.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
         
         
    }
     
     
      public  Connection getConnection() throws SQLException {
          Connection connection = ds.getConnection();
          return connection;
      }
      
 
}

简单配置:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybase
username=root
password=abc123
initialSize=5
maxActive=10
maxWait=3000
maxIdle=8
minIdle=3

 参考连接

https://www.cnblogs.com/yankang/p/11053168.html

https://www.cnblogs.com/liuys635/p/14307151.html

http://www.manongjc.com/detail/22-mezpdpexqxfqelr.html

原文地址:https://www.cnblogs.com/kpwong/p/15760581.html