/**
 * DataSource工具类
 */
public class DataSourceUtils {

    //1、构造方法私有化
    private DataSourceUtils() {
    }

    //2、声明所需的配置变量
    private static DataSource dataSource;    //注册驱动的信息

    //3、提供静态代码块,读取配置文件的信息,注册驱动
    static {
        try {
            //加载配置文件
            InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream("config.properties");
            Properties prop = new Properties();
            prop.load(is);
            //获取数据源(连接池对象)
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //4、提供获取数据库连接方法
    public static Connection getConnection() {
        Connection con = null;
        try {
            con = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }

    //5、提供获取数据源(连接池对象)方法
    public static DataSource getDataSource(){
        return  dataSource;
    }

    //6、提供释放资源方法
    public static void close(Connection con, Statement stst, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (stst != null) {
            try {
                stst.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}