|
|
|
package com.xydl.util;
|
|
|
|
|
|
|
|
import com.alibaba.druid.pool.DruidDataSource;
|
|
|
|
import com.alibaba.druid.pool.DruidDataSourceFactory;
|
|
|
|
import org.slf4j.Logger;
|
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
|
|
|
|
import javax.sql.DataSource;
|
|
|
|
import java.sql.*;
|
|
|
|
import java.util.Properties;
|
|
|
|
|
|
|
|
public class DataSourceUtils {
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(DataSourceUtils.class);
|
|
|
|
private static DataSource dataSource;
|
|
|
|
private static String url;
|
|
|
|
|
|
|
|
static {
|
|
|
|
initDataSource();
|
|
|
|
}
|
|
|
|
|
|
|
|
private static void initDataSource() {
|
|
|
|
Properties properties = new Properties();
|
|
|
|
properties.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");
|
|
|
|
properties.setProperty("url", "jdbc:mysql://localhost:3306/cac");
|
|
|
|
properties.setProperty("username", "root");
|
|
|
|
properties.setProperty("password", "root");
|
|
|
|
|
|
|
|
try {
|
|
|
|
dataSource = DruidDataSourceFactory.createDataSource(properties);
|
|
|
|
url = ((DruidDataSource) dataSource).getUrl();
|
|
|
|
} catch (Exception e) {
|
|
|
|
logger.error("init dataSource exception:", e);
|
|
|
|
}
|
|
|
|
logger.info("Data source has been initialized successfully!");
|
|
|
|
}
|
|
|
|
|
|
|
|
// 提供获取连接的方法
|
|
|
|
public static Connection getConnection() throws SQLException {
|
|
|
|
return dataSource.getConnection();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 提供关闭资源的方法【connection是归还到连接池】
|
|
|
|
// 提供关闭资源的方法 【方法重载】3 dql
|
|
|
|
public static void closeResource(ResultSet resultSet, Statement statement, Connection connection) {
|
|
|
|
// 关闭结果集
|
|
|
|
closeResultSet(resultSet);
|
|
|
|
// 关闭语句执行者
|
|
|
|
closeStatement(statement);
|
|
|
|
// 关闭连接
|
|
|
|
closeConnection(connection);
|
|
|
|
}
|
|
|
|
|
|
|
|
// 提供关闭资源的方法 【方法重载】 2 dml
|
|
|
|
public static void closeResource(Statement statement, Connection connection) {
|
|
|
|
// 关闭语句执行者
|
|
|
|
closeStatement(statement);
|
|
|
|
// 关闭连接
|
|
|
|
closeConnection(connection);
|
|
|
|
}
|
|
|
|
|
|
|
|
private static void closeConnection(Connection connection) {
|
|
|
|
if (connection != null) {
|
|
|
|
try {
|
|
|
|
connection.close();
|
|
|
|
} catch (SQLException e) {
|
|
|
|
logger.error("closeConnection exception", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static void closeStatement(Statement statement) {
|
|
|
|
if (statement != null) {
|
|
|
|
try {
|
|
|
|
statement.close();
|
|
|
|
} catch (SQLException e) {
|
|
|
|
logger.error("closeStatement exception", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static void closeResultSet(ResultSet resultSet) {
|
|
|
|
if (resultSet != null) {
|
|
|
|
try {
|
|
|
|
resultSet.close();
|
|
|
|
} catch (SQLException e) {
|
|
|
|
logger.error("closeResultSet exception", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|