Druid
public class Druid {
public static DruidDataSource dataSource;
static {
try {
Properties properties = new Properties();
InputStream inputStream = Druid.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(inputStream);
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
HikariCP
public class HikariCP {
public static HikariDataSource dataSource=null;
static {
try {
HikariConfig config=new HikariConfig("/HikariCp.properties");
dataSource=new HikariDataSource(config);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Test
import DBUtils.Druid;
import DBUtils.HikariCP;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtilsTest {
@Test
public void DruidTest() throws SQLException {
String sql="select * from person";
Connection conn=Druid.getConnection();
PreparedStatement preparedStatement=conn.prepareStatement(sql);
ResultSet resultSet=preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getInt(1)+resultSet.getString(2)+resultSet.getInt(3));
}
Druid.closeAll(conn,preparedStatement,resultSet);
}
@Test
public void HikariCPTest() throws SQLException {
System.out.println(1);
String sql="select * from person";
System.out.println(2);
Connection connection= HikariCP.getConnection();
PreparedStatement preparedStatement=connection.prepareStatement(sql);
ResultSet resultSet=preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getInt(1)+resultSet.getString(2)+resultSet.getInt(3));
}
HikariCP.closeAll(connection,preparedStatement,resultSet);
}
}