Java教程

使用Druid和Hikari连接数据库

本文主要是介绍使用Druid和Hikari连接数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

以前大多使用C3P0和JDBC,单这连个有点老了,现在比较常用的是Druid和Hikari,Druid是阿里的,Hikari是日本的,Druid功能强大,Hikari查询起来比较快

1、新建jdbc.properties,hikari.properties

除了常规一定要设置的前四项,还要设置后四项

druid.username=root
druid.password=123456
druid.url=jdbc:mysql://127.0.0.1:3306/aa?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false
druid.driverClassName=com.mysql.cj.jdbc.Driver
druid.keepAlive=300
druid.maxWait=300
druid.initialSize=10
druid.maxActive=20
username=root
password=123456
jdbcUrl=jdbc:mysql://127.0.0.1:3306/aa?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false
driverClassName=com.mysql.cj.jdbc.Driver

2、新建PoolTest.java

public class PoolTest {

    @Test
    public void test1() throws Exception{

        Properties properties = new Properties();
        properties.load(PoolTest.class.getClassLoader().getResourceAsStream("jdbc.properties"));

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.configFromPropety(properties);

        //DruidPooledConnection connection = druidDataSource.getConnection();

        Connection connection = druidDataSource.getConnection();
        System.out.println(druidDataSource.getCreateCount());
    }

    @Test
    public void test2() throws Exception{

        Properties properties = new Properties();
        properties.load(PoolTest.class.getClassLoader().getResourceAsStream("hikari.properties"));


        HikariConfig hikariConfig = new HikariConfig(properties);
        DataSource dataSource = new HikariDataSource(hikariConfig);

        System.out.println(dataSource.getConnection());
    }

    @Test
    public void test3() throws Exception{
        //System.out.println(DataSourceUtil.DATASOURCE.getConnection());
    }
}

这篇关于使用Druid和Hikari连接数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!