0

I have a stand alone Java Program [ No application server/session involved] using Oracle DB connection and BoneCP . I need to run different Queries from different methods and I don't want the DB connection/pool created in each call.

I have a DBManager class where the connection pool is created. I would like to know how exactly I can reuse the connection object created to run mutiple queries from different classes/methods.

try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    try {

        // setup the connection pool
        BoneCPConfig config = new BoneCPConfig();
        config.setJdbcUrl( "jdbc:oracle:thin:@"+prop.getProperty(DB_HOST)+":"+prop.getProperty(DB_PORT)+":"+prop.getProperty(DB_INSTANCE)); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
        config.setUsername( prop.getProperty(APP_DB_USER)); 
        config.setPassword(prop.getProperty(APP_DB_PWD));
        config.setMinConnectionsPerPartition(5);
        config.setMaxConnectionsPerPartition(10);
        config.setPartitionCount(1);
        connectionPool = new BoneCP(config); // setup the connection pool

        connection = connectionPool.getConnection(); // fetch a connection

If I call the object of this class / even if its a static class won't the CP get created every time ? Hoew exactly I can reuse the connection object by creating the connection only once ?

Thanks in advance.

  • I just now saw https://stackoverflow.com/questions/6944810/using-bonecp-handling-connections-from-the-pool?rq=1" related question. But I just wanted to confirm if the correct way is to use my class as a singleton or any other better options are there. – Santhosh Kaitheri Jul 20 '17 at 09:59

1 Answers1

0

Your best option is to use a singleton class.

The next best option is to run your java program on a server (e.g. tomcat) and let the server handle the db connection pool for you.

You may also want to try hikaricp connection pool as it is a very quick and clean connection pool implementation!

komarios
  • 147
  • 4