Daya
Daya

Reputation: 11

Multiple Oracle DB connections with OracleDataSource

This code is pseudo code

Trying to execute the method executeAllTheQueries(). But am seeing number of db connections are equal to the size of ArrayList<String> queries. Ideally it should be only once. what's going wrong here?

 

    public class Database {
       Connection conneciton = null;
       protected OracleDataSource ds;

       public Database(String connectString, String user, String password) throws SQLException {

          ds = new OracleDataSource();
          ds.setURL(connectString);
          ds.setUser(user);
          ds.setPassword(password);
       }

       //Method to open the connection if there isn’t one
       public Connection createConnection() throws SQLException {
         this.connection = (connection == null) ? ds.getConnection() : this.connection;
       }

       //Method to close the db connection
       protected void closeConnection() throws SQLException {
        if (connection != null) {
            connection.close();
            this.connection = null;
        }
       }

       //Method to do something
       public String doSomething(String query) {
          createConnection();
          //Doing something
       }


    //Class to execute all the queries
    public class ExecuteQueries {
         private ArrayList queries;
         Database db;

        public ExecuteQueries(ArrayList queries, Database db) { 
          this.queries = queries ;
          this.db = db;
        }

      public ArrayList executeAllTheQueries() {
           for (String query: this.queries) {
              db.doSomething(query);
           }
      }

    }


Upvotes: 1

Views: 290

Answers (1)

Yuriy Vinogradov
Yuriy Vinogradov

Reputation: 523

Looks like You create connection in every call to doSomething. And you call doSomething for every query.

Upvotes: 0

Related Questions