数据库连接池工具类 JdbcUtils

数据库连接池工具类 JdbcUtils

public class JdbcUtils {
    private static DataSource ds;
    /*
	静态代码块
		1、加载配置文件
		2、获取数据库连接池
*/
       static{
        Properties prop = new Properties();
        InputStream rs = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            prop.load(rs);
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    //获取数据库连接池的方法
    public static DataSource getDataSource(){
        return ds;
    }
    //关闭资源
    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //获取连接对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45889221/article/details/107593785