手動寫一個簡單的數據庫連接池:

public class DBConnectionPool {

    private static int MIN_SIZE = 2;

    private static int MAX_SIZE = 5;

    private static Vector pool = new Vector();

    static {

           for(int i=0; i<MIN_SIZE; i++) {

                  pool.add(createConnection());

           }

    }

    private static Connection createConnection() {

           Connection conn = null;

           try {

                  Class.forName("oracle.jdbc.driver.OracleDriver");

                  conn = DriverManager.getConnection(

                                "jdbc:oracle:thin:@192.168.0.73:1521:bjsxt", "cms", "cms");

           } catch (ClassNotFoundException e) {

                  e.printStackTrace();

           } catch (SQLException e) {

                  e.printStackTrace();

           }

           return conn;

    }

    public static Connection getConnection() {

           Connection conn = null;

           int last_index = pool.size() - 1;

           if(pool.isEmpty()) {

                  conn = createConnection();

           } else {

                  conn = (Connection)pool.remove(last_index);

           }

           return conn;

    }

    public static void close(Connection conn) throws SQLException {

           if(pool.size() < MAX_SIZE) {

                  pool.add(conn);

           } else {

                  conn.close();

           }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章