DBCP工具类(java)

tech2023-09-05  88

/**

DBCP工具类使用静态代码块来实现单例模式@author 11561

*/ 导包:

private static DBCPUtil2 INSTANCE = null; private static DataSource dataSource = null; /** * 私有化构造方法 */ private DBCPUtil2() { // TODO Auto-generated constructor stub } //静态代码块先执行 static{ //获得配置文件 Properties properties = new Properties(); try { //获得配置文件信息 properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("dbcp.properties")); dataSource = BasicDataSourceFactory.createDataSource(properties); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //创建一个工具类对象 返回给静态成员变量单例 INSTANCE = new DBCPUtil2(); } /** * 公开静态方法获取单例 * @return */ public static DBCPUtil2 getInstance() { return INSTANCE; } /** * 获取连接的方法 * @return */ public Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 释放资源的方法 * @param statement * @param connection * @param resultSet */ public void close(Statement statement,Connection connection,ResultSet resultSet) { try { if (resultSet!= null) { resultSet.close(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally { if (connection != null) { try { connection.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } } } /** * 释放资源的方法 * @param statement * @param connection */ public void close(Statement statement,Connection connection) { this.close(statement, connection,null); }
最新回复(0)