与OracleDataSource的多个Oracle DB连接

时间:2016-06-28 15:22:21

标签: java

此代码为伪代码

尝试执行方法executeAllTheQueries()。但我看到数据库连接的数量等于ArrayList<String> queries的大小。理想情况下它应该只有一次。这里出了什么问题?

 

    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);
           }
      }

    }


1 个答案:

答案 0 :(得分:0)

看起来您在每次调用doSomething时都会创建连接。你为每个查询调用doSomething。