1. 程式人生 > >Apache Commons 工具類介紹

Apache Commons 工具類介紹

//官方示例  
    public class PoolingDataSources {  
      
        public static void main(String[] args) {  
            System.out.println("載入jdbc驅動");  
            try {  
            Class.forName("oracle.jdbc.driver.OracleDriver");  
            } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
            }  
            System.out.println("Done.");  
            //  
            System.out.println("設定資料來源");  
            DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");  
            System.out.println("Done.");  
              
            //  
            Connection conn = null;  
            Statement stmt = null;  
            ResultSet rset = null;  
              
            try {  
            System.out.println("Creating connection.");  
            conn = dataSource.getConnection();  
            System.out.println("Creating statement.");  
            stmt = conn.createStatement();  
            System.out.println("Executing statement.");  
            rset = stmt.executeQuery("select * from person");  
            System.out.println("Results:");  
            int numcols = rset.getMetaData().getColumnCount();  
            while(rset.next()) {  
            for(int i=0;i<=numcols;i++) {  
            System.out.print("\t" + rset.getString(i));  
            }  
            System.out.println("");  
            }  
            } catch(SQLException e) {  
            e.printStackTrace();  
            } finally {  
            try { if (rset != null) rset.close(); } catch(Exception e) { }  
            try { if (stmt != null) stmt.close(); } catch(Exception e) { }  
            try { if (conn != null) conn.close(); } catch(Exception e) { }  
            }  
            }  
      
        public static DataSource setupDataSource(String connectURI) {  
            //設定連線地址  
            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(  
                    connectURI, null);  
      
            // 建立連線工廠  
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(  
                    connectionFactory);  
      
            //獲取GenericObjectPool 連線的例項  
            ObjectPool connectionPool = new GenericObjectPool(  
                    poolableConnectionFactory);  
      
            // 建立 PoolingDriver  
            PoolingDataSource dataSource = new PoolingDataSource(connectionPool);  
              
            return dataSource;  
        }  
    }