duird连接池的配置

1、druid配置

  • 纯代码方式
//数据源配置
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1/db_student?serverTimezone=UTC");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); //这个可以缺省的,会根据url自动识别
        dataSource.setUsername("root");
        dataSource.setPassword("abcd");
        
        //下面都是可选的配置
        dataSource.setInitialSize(10);  //初始连接数,默认0
        dataSource.setMaxActive(30);  //最大连接数,默认8
        dataSource.setMinIdle(10);  //最小闲置数
        dataSource.setMaxWait(2000);  //获取连接的最大等待时间,单位毫秒
        dataSource.setPoolPreparedStatements(true); //缓存PreparedStatement,默认false
        dataSource.setMaxOpenPreparedStatements(20); //缓存PreparedStatement的最大数量,默认-1(不缓存)。大于0时会自动开启缓存PreparedStatement,所以可以省略上一句代码

        //获取连接
        Connection connection = dataSource.getConnection();

        //Statement接口
        Statement statement = connection.createStatement();
        String sql1 = "insert into tb_student (name,age) values ('chy',20)";
        statement.executeUpdate(sql1);

        //PreparedStatement接口
        String sql2 = "insert into tb_student (name,age) values ('chy',21)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql2);
        preparedStatement.execute();

        //关闭连接
        connection.close();
  • properties方式
url=jdbc:mysql://127.0.0.1/db_student?serverTimezone=UTC
#这个可以缺省的,会根据url自动识别
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=abcd

##初始连接数,默认0
initialSize=10
#最大连接数,默认8
maxActive=30
#最小闲置数
minIdle=10
#获取连接的最大等待时间,单位毫秒
maxWait=2000
#缓存PreparedStatement,默认false
poolPreparedStatements=true
#缓存PreparedStatement的最大数量,默认-1(不缓存)。大于0时会自动开启缓存PreparedStatement,所以可以省略上一句设置
maxOpenPreparedStatements=20
  • yml方式
spring:
  datasource:
    url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example?serverTimezone=Asia/Shanghai
    username: springuser
    password: test123
    jpa:
      database-platform: org.hibernate.dialect.MySQLDialect
    druid:
      initial-size: 1
      min-idle: 1
      max-active: 20
      max-wait: 60000
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      validation-query: select 1 from dual
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      keep-alive: true

猜你喜欢

转载自blog.csdn.net/x1339874968/article/details/119186737