一、依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>yofc</groupId> <artifactId>jdbc</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.26</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- 指定jdk --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
二、获取连接
1.无配置文件
@Test public void testHikariCP() throws SQLException { HikariConfig config = new HikariConfig(); config.setDriverClassName("com.mysql.cj.jdbc.Driver"); config.setJdbcUrl("jdbc:mysql://192.168.8.136:3306/jdbc"); config.setUsername("root"); config.setPassword("root"); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // HikariDataSource 也可以配置 DataSource ds = new HikariDataSource(config); ((HikariDataSource) ds).setPassword("root"); System.out.println(ds.getConnection()); ((HikariDataSource) ds).close(); }
2.有配置文件
hikaricp.properties
jdbcUrl=jdbc:mysql://192.168.8.136:3306/jdbc dataSource.user=root dataSource.password=root dataSource.databaseName=jdbc
@Test public void testHikariCPWithConfig() throws SQLException { Properties props = new Properties(); props.setProperty("dataSourceClassName", "org.postgresql.ds.PGSimpleDataSource"); props.setProperty("dataSource.user", "test"); props.setProperty("dataSource.password", "test"); props.setProperty("dataSource.databaseName", "mydb"); props.put("dataSource.logWriter", new PrintWriter(System.out)); // HikariConfig config = new HikariConfig(props); HikariConfig config = new HikariConfig(this.getClass().getClassLoader().getResource("hikaricp.properties").getPath()); HikariDataSource ds = new HikariDataSource(config); System.out.println(ds.getConnection()); ((HikariDataSource) ds).close(); }