C3P0非XML实例

  1. public class DBPool {  
  2.     private static DBPool dbPool;  
  3.     private ComboPooledDataSource dataSource;  
  4.   
  5.     static {  
  6.         dbPool = new DBPool();  
  7.     }  
  8.   
  9.     public DBPool() {  
  10.         try {  
  11.             dataSource = new ComboPooledDataSource();  
  12.             dataSource.setUser("root");  
  13.             dataSource.setPassword("123456");  
  14.             dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/game?user=root&password=123456&useUnicode=true");  
  15.             dataSource.setDriverClass("com.mysql.jdbc.Driver");  
  16.             // 设置初始连接池的大小!  
  17.             dataSource.setInitialPoolSize(2);  
  18.             // 设置连接池的最小值!   
  19.             dataSource.setMinPoolSize(1);  
  20.             // 设置连接池的最大值!   
  21.             dataSource.setMaxPoolSize(10);  
  22.             // 设置连接池中的最大Statements数量!  
  23.             dataSource.setMaxStatements(50);  
  24.             // 设置连接池的最大空闲时间!  
  25.             dataSource.setMaxIdleTime(60);  
  26.         } catch (PropertyVetoException e) {  
  27.             throw new RuntimeException(e);  
  28.         }  
  29.     }  
  30.   
  31.     public final static DBPool getInstance() {  
  32.         return dbPool;  
  33.     }  
  34.   
  35.     public final Connection getConnection() {  
  36.         try {  
  37.             return dataSource.getConnection();  
  38.         } catch (SQLException e) {  
  39.             throw new RuntimeException("无法从数据源获取连接 ", e);  
  40.         }  
  41.     }  
  42.   
  43.     public static void main(String[] args) throws SQLException {  
  44.         Connection con = null;  
  45.         try {  
  46.             con = DBPool.getInstance().getConnection();  
  47.             ResultSet rs = con.createStatement().executeQuery("SELECT * FROM LESOGO_USER");  
  48.             while (rs.next()) {  
  49.                 System.out.println(rs.getObject(1));  
  50.                 System.out.println(rs.getObject(2));  
  51.                 System.out.println(rs.getObject(3));  
  52.             }  
  53.         } catch (Exception e) {  
  54.         } finally {  
  55.             if (con != null)  
  56.                 con.close();  
  57.         }  
  58.     }  
  59. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值