Java代码  Java使用独立数据库连接池(DBCP为例)
  1. //持有一个静态的数据库连接池对象  
  2. private static DataSource DS;  
  3.   
  4.   
  5. //使用DBCP提供的BasicDataSource实现DataSource接口  
  6. public static void initDataSource(String connectURI, String username,  
  7.             String password, String driverClass, int initialSize,  
  8.             int maxActive, int maxIdle, int maxWait) {  
  9.                   BasicDataSource ds = new BasicDataSource();  
  10.         ds.setDriverClassName(driverClass);  
  11.         ds.setUsername(username);  
  12.         ds.setPassword(password);  
  13.         ds.setUrl(connectURI);  
  14.         ds.setInitialSize(initialSize);  
  15.         ds.setMaxActive(maxActive);  
  16.         ds.setMaxIdle(maxIdle);  
  17.         ds.setMaxWait(maxWait);  
  18.         DS = ds;  
  19.     }  
  20. //获得一个数据库连接  
  21. public Connection getConnection() {  
  22.   
  23.         Connection con = null;  
  24.         if (DS != null) {  
  25.             try {  
  26.                 con = DS.getConnection();  
  27.             } catch (Exception e) {  
  28.                 System.out.println(e.getMessage());         }  
  29.                            //将数据库连接的事物设置为不默认为自动Commit  
  30.             try {  
  31.                 con.setAutoCommit(false);  
  32.             } catch (SQLException e) {  
  33.                 System.out.println(e.getMessage());         }  
  34.             return con;  
  35.         }  
  36.                   //回收数据库连接时,直接使用con.close()即可  
  37.         return con;  
  38.   
  39.     }  
  40.   
  41. //回收数据库连接  
  42.     protected static void shutdownDataSource() throws SQLException {  
  43.         BasicDataSource bds = (BasicDataSource) DS;  
  44.         bds.close();  
  45.     }  


上面的代码都是从实际使用的代码抽取出来的,希望可以帮助大家。 

目前,OpenSource中提供了很多的数据库连接池技术,使用的流程和模式,都与上面的代码大同小异。同时最新发布的BoneCP我还从来没有感受过,希望有朋友与我分享一下使用经验。 

相关文章:

  • 2022-03-09
  • 2021-07-02
  • 2021-12-01
  • 2022-12-23
  • 2022-12-23
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2021-11-08
  • 2021-10-27
  • 2021-11-19
  • 2021-06-07
  • 2022-01-10
相关资源
相似解决方案