package common;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.*;
import java.sql.*;
import java.util.Properties;


/**
 * 这是一个数据库工具类，创建了一个数据库连接池
 * 需要在database.properties中配置数据库连接属性
 * @author Awin-x
 */
public class DBTool {
    static DataSource ds;
    static{
        Properties prop = new Properties();
        try {
            InputStream database_info = DBTool.class.getClassLoader().getResourceAsStream("database.properties");
            if (database_info != null) {
                prop.load(new InputStreamReader(database_info, "GBK"));
                prop.list(System.out);
            }else{
                throw new FileNotFoundException("database.properties file does not exist in the classpath");
            }
        } catch (IOException e) {
            System.out.println("数据库配置加载失败！");
            throw new RuntimeException(e);
        }
        try {
            ds = BasicDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            System.out.println("数据库连接池初始化失败");
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(){
        try{
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static PreparedStatement getPreparedStatement(String sql) throws SQLException{
        //noinspection SqlSourceToSinkFlow
        return ds.getConnection().prepareStatement(sql);
    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        try{
            if(rs != null){
                rs.close();
            }
            if(ps != null){
                ps.close();
            }
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            System.out.println("关闭失败");
            e.printStackTrace();
        }
    }

    public static void close(PreparedStatement ps, ResultSet rs){
        close(null, ps, rs);
    }

    public static void close(PreparedStatement ps){
        close(null, ps, null);
    }
}
