<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.2</version>
</dependency>
package com.dxy.study_0628.study.hikari;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class HikariTest {
/**
* Hikari 加载数据库连接
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException, IOException {
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(2);
config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
config.addDataSourceProperty("serverName", "39.102.42.35");
config.addDataSourceProperty("port", 3306);
config.addDataSourceProperty("databaseName", "caiwu");
config.addDataSourceProperty("user", "root");
config.addDataSourceProperty("password", "root");
HikariDataSource dataSource = new HikariDataSource(config);
//Connection connection = dataSource.getConnection();
Connection connection = HikariTest.getConnection();
Statement statement = connection.createStatement();
// 要执行的SQL语句id和content是表review中的项。
String sql = "select * from c_user";
// 得到结果
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
String username = rs.getString("username");
System.out.println("Logon"+username);
}
}
public static Connection getConnection() throws IOException, SQLException {
Properties properties = new Properties();
//InputStream in = HikariTest.class.getClass().getResourceAsStream("src/main/resources/application.properties");
InputStream in = new BufferedInputStream(new FileInputStream("src/main/resources/application.properties"));
properties.load(in);
String username = properties.getProperty("spring.datasource.username");
String port = properties.getProperty("server.port");
String password = properties.getProperty("spring.datasource.password");
String name = properties.getProperty("spring.application.name");
System.out.println("项目端口:"+port+",项目名称:"+name);
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(2);
config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
config.addDataSourceProperty("serverName", "39.102.42.235");
config.addDataSourceProperty("port", 3306);
config.addDataSourceProperty("databaseName", "cai1wu");
config.addDataSourceProperty("user", username);
config.addDataSourceProperty("password", password);
HikariDataSource dataSource = new HikariDataSource(config);
Connection connection = dataSource.getConnection();
return connection;
}
}
参考
https://www.cnblogs.com/diandianquanquan/p/10607021.html