예제 #1
0
  /*
   * Similar to makeSureValInRange function except it is meant to return
   * more than one values of valid user input via LinkedList and it will
   * not return unless all of the input is valid
   * @param1 scanner object
   * @param2 lowerbound int
   * @param3 upperbound int
   * @param4 String that represents the entity we are entering the values for
   */
  public static LinkedList<Integer> makeSureValInRange2(
      Scanner scan, int lowerbound, int upperbound, String inputFor) {
    assert (lowerbound <= upperbound);
    LinkedList<Integer> list = new LinkedList<Integer>();
    System.out.println(
        SearchCriteria.prioritySetUpString(
            SearchCriteria.StringEnum.SELECT_CRITERIA, inputFor)); // prints the options to the user
    int value = scan.nextInt();
    if (valInRange(lowerbound, upperbound, value)) {
      list.add(value); // If the first inputted is in range then we add more values

      boolean done = false;
      int i = lowerbound;
      while (!done
          && i < upperbound) { // keep looking for input until user enters a duplicate value
        // or the LinkedList of input is full
        value = scan.nextInt();
        if (!list.contains(value) && valInRange(lowerbound, upperbound, value)) list.add(value);
        else done = true;
        i++;
      }
      return list;
    } else { // If the first value intered is not valid, then we return a null, which means that
      // we use default values (all values within range)
      System.out.println(
          SearchCriteria.prioritySetUpString(SearchCriteria.StringEnum.DEFAULT, inputFor));
      return null;
    }
  }
 public void deleteNumberDefByNextIdx(
     CFSecurityAuthorization Authorization, CFDbTestValueByNextIdxKey argKey) {
   final String S_ProcName = "deleteNumberDefByNextIdx";
   CFDbTestNumberDefBuff cur;
   LinkedList<CFDbTestNumberDefBuff> matchSet = new LinkedList<CFDbTestNumberDefBuff>();
   Iterator<CFDbTestNumberDefBuff> values = dictByPKey.values().iterator();
   while (values.hasNext()) {
     cur = values.next();
     if (argKey.equals(cur)) {
       matchSet.add(cur);
     }
   }
   Iterator<CFDbTestNumberDefBuff> iterMatch = matchSet.iterator();
   while (iterMatch.hasNext()) {
     cur = iterMatch.next();
     String subClassCode = cur.getClassCode();
     if ("NUMD".equals(subClassCode)) {
       schema.getTableNumberDef().deleteNumberDef(Authorization, cur);
     } else if ("NUMC".equals(subClassCode)) {
       schema.getTableNumberCol().deleteNumberCol(Authorization, (CFDbTestNumberColBuff) cur);
     } else if ("NUMT".equals(subClassCode)) {
       schema.getTableNumberType().deleteNumberType(Authorization, (CFDbTestNumberTypeBuff) cur);
     } else {
       throw CFLib.getDefaultExceptionFactory()
           .newUnsupportedClassException(
               getClass(),
               S_ProcName,
               "subClassCode",
               cur,
               "Instance of or subclass of NumberDef must not be \"" + subClassCode + "\"");
     }
   }
 }
예제 #3
0
  public void parseInputFile(File inputFile) throws IOException {
    geneFeatures.clear();
    otherRecords.clear();

    try {
      GFFEntrySet gffEntries = GFFTools.readGFF(inputFile);

      Iterator itr = gffEntries.lineIterator();
      int count = 0;
      int intronFeatures = 0;
      LinkedList<GFFRecord> cdsRecs = new LinkedList<GFFRecord>();

      while (itr.hasNext()) {
        Object val = itr.next();
        if (val instanceof GFFRecord) {
          GFFRecord rec = (GFFRecord) val;
          count += 1;

          if (rec.getFeature().endsWith("gene")) {
            GeneFeatures gf = new GeneFeatures(rec);
            geneFeatures.put(gf.id, gf);
          } else if (rec.getFeature().equals("CDS")) {
            cdsRecs.addLast(rec);
          } else {
            otherRecords.add(rec);
          }
        }
      }

      for (GFFRecord rec : cdsRecs) {
        Map<String, List<String>> attrs = decodeAttrMap(rec);
        if (geneFeatures.containsKey(attrs.get("Parent").get(0))) {
          geneFeatures.get(attrs.get("Parent").get(0)).addCDS(rec, attrs);
        } else {
          System.err.println("Unknown CDS Parent: " + attrs.get("Parent").get(0));
        }
      }

      for (String k : geneFeatures.keySet()) {
        GeneFeatures gf = geneFeatures.get(k);
        if (gf.cds != null && gf.cds.size() > 1) {
          intronFeatures++;
        }
      }

      System.err.println("# GFF Records: " + count);
      System.err.println("# Gene Feature Sets: " + geneFeatures.size());
      System.err.println("\t# Intron-Features: " + intronFeatures);

    } catch (ParserException e) {
      e.printStackTrace();
    } catch (BioException e) {
      e.printStackTrace();
    }
  }
  public Collection<ExptCondition> getAllConditions() throws SQLException {
    LinkedList<Integer> conds = new LinkedList<Integer>();
    Statement s = cxn.createStatement();
    ResultSet rs = s.executeQuery("select distinct(e.condition) from experiment e");

    while (rs.next()) {
      conds.add(rs.getInt(1));
    }

    rs.close();
    s.close();

    return loader.loadAllExptConditions(conds);
  }
예제 #5
0
 public Iterator<String> execute(String input) {
   try {
     ps.setString(1, input);
     ResultSet rs = ps.executeQuery();
     LinkedList<String> results = new LinkedList<String>();
     while (rs.next()) {
       results.add(rs.getString(1));
     }
     rs.close();
     return results.iterator();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   return new EmptyIterator<String>();
 }
예제 #6
0
 @Override
 public Iterator<TickClient> getLocalItems(int itemTypes, Room R) {
   LinkedList<TickClient> localItems = null;
   for (TickClient C : tickers) {
     switch (itemTypes) {
       case 0:
         if (C.getClientObject() instanceof MOB) {
           if (((MOB) C.getClientObject()).getStartRoom() == R) {
             if (localItems == null) localItems = new LinkedList<TickClient>();
             localItems.add(C);
           }
         } else if ((C.getClientObject() instanceof ItemTicker)
             && ((((ItemTicker) C.getClientObject()).properLocation() == R))) {
           if (localItems == null) localItems = new LinkedList<TickClient>();
           localItems.add(C);
         }
         break;
       case 1:
         if ((C.getClientObject() instanceof ItemTicker)
             && ((((ItemTicker) C.getClientObject()).properLocation() == R))) {
           if (localItems == null) localItems = new LinkedList<TickClient>();
           localItems.add(C);
         }
         break;
       case 2:
         if ((C.getClientObject() instanceof MOB)
             && (((MOB) C.getClientObject()).getStartRoom() == R)) {
           if (localItems == null) localItems = new LinkedList<TickClient>();
           localItems.add(C);
         }
         break;
     }
   }
   if (localItems == null) return null;
   return localItems.iterator();
 }
 public void deleteFeeByIdIdx(CFSecurityAuthorization Authorization, CFAccFeePKey argKey) {
   CFAccFeeBuff cur;
   LinkedList<CFAccFeeBuff> matchSet = new LinkedList<CFAccFeeBuff>();
   Iterator<CFAccFeeBuff> values = dictByPKey.values().iterator();
   while (values.hasNext()) {
     cur = values.next();
     if (argKey.equals(cur)) {
       matchSet.add(cur);
     }
   }
   Iterator<CFAccFeeBuff> iterMatch = matchSet.iterator();
   while (iterMatch.hasNext()) {
     cur = iterMatch.next();
     deleteFee(Authorization, cur);
   }
 }
 public void deleteDelSubDep3ByIdIdx(CFBamAuthorization Authorization, CFBamScopePKey argKey) {
   CFBamDelSubDep3Buff cur;
   LinkedList<CFBamDelSubDep3Buff> matchSet = new LinkedList<CFBamDelSubDep3Buff>();
   Iterator<CFBamDelSubDep3Buff> values = dictByPKey.values().iterator();
   while (values.hasNext()) {
     cur = values.next();
     if (argKey.equals(cur)) {
       matchSet.add(cur);
     }
   }
   Iterator<CFBamDelSubDep3Buff> iterMatch = matchSet.iterator();
   while (iterMatch.hasNext()) {
     cur = iterMatch.next();
     deleteDelSubDep3(Authorization, cur);
   }
 }
 public void deleteISOCurrencyByCcyNmIdx(
     CFBamAuthorization Authorization, CFBamISOCurrencyByCcyNmIdxKey argKey) {
   CFBamISOCurrencyBuff cur;
   LinkedList<CFBamISOCurrencyBuff> matchSet = new LinkedList<CFBamISOCurrencyBuff>();
   Iterator<CFBamISOCurrencyBuff> values = dictByPKey.values().iterator();
   while (values.hasNext()) {
     cur = values.next();
     if (argKey.equals(cur)) {
       matchSet.add(cur);
     }
   }
   Iterator<CFBamISOCurrencyBuff> iterMatch = matchSet.iterator();
   while (iterMatch.hasNext()) {
     cur = iterMatch.next();
     deleteISOCurrency(Authorization, cur);
   }
 }
 public void deleteLoaderBehaviourByUNameIdx(
     CFSecurityAuthorization Authorization, CFDbTestLoaderBehaviourByUNameIdxKey argKey) {
   CFDbTestLoaderBehaviourBuff cur;
   LinkedList<CFDbTestLoaderBehaviourBuff> matchSet =
       new LinkedList<CFDbTestLoaderBehaviourBuff>();
   Iterator<CFDbTestLoaderBehaviourBuff> values = dictByPKey.values().iterator();
   while (values.hasNext()) {
     cur = values.next();
     if (argKey.equals(cur)) {
       matchSet.add(cur);
     }
   }
   Iterator<CFDbTestLoaderBehaviourBuff> iterMatch = matchSet.iterator();
   while (iterMatch.hasNext()) {
     cur = iterMatch.next();
     deleteLoaderBehaviour(Authorization, cur);
   }
 }
  /**
   * Preconditions: 1. flag must be one of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS or TMSTARTTRSCAN |
   * TMENDRSCAN 2. if flag isn't TMSTARTRSCAN or TMSTARTRSCAN | TMENDRSCAN, a recovery scan must be
   * in progress
   *
   * <p>Postconditions: 1. list of prepared xids is returned
   */
  public Xid[] recover(int flag) throws XAException {
    // Check preconditions
    if (flag != TMSTARTRSCAN
        && flag != TMENDRSCAN
        && flag != TMNOFLAGS
        && flag != (TMSTARTRSCAN | TMENDRSCAN))
      throw new PGXAException(GT.tr("Invalid flag"), XAException.XAER_INVAL);

    // We don't check for precondition 2, because we would have to add some additional state in
    // this object to keep track of recovery scans.

    // All clear. We return all the xids in the first TMSTARTRSCAN call, and always return
    // an empty array otherwise.
    if ((flag & TMSTARTRSCAN) == 0) return new Xid[0];
    else {
      try {
        Statement stmt = conn.createStatement();
        try {
          // If this connection is simultaneously used for a transaction,
          // this query gets executed inside that transaction. It's OK,
          // except if the transaction is in abort-only state and the
          // backed refuses to process new queries. Hopefully not a problem
          // in practise.
          ResultSet rs = stmt.executeQuery("SELECT gid FROM pg_prepared_xacts");
          LinkedList l = new LinkedList();
          while (rs.next()) {
            Xid recoveredXid = RecoveredXid.stringToXid(rs.getString(1));
            if (recoveredXid != null) l.add(recoveredXid);
          }
          rs.close();

          return (Xid[]) l.toArray(new Xid[l.size()]);
        } finally {
          stmt.close();
        }
      } catch (SQLException ex) {
        throw new PGXAException(GT.tr("Error during recover"), ex, XAException.XAER_RMERR);
      }
    }
  }
예제 #12
0
  public static synchronized Connection getConnection() {
    clearClosedConnection();
    while (m_notUsedConnection.size() > 0) {
      try {
        ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst();
        if (wrapper.connection.isClosed()) {
          continue;
        }
        m_usedUsedConnection.add(wrapper);
        if (DEBUG) {
          wrapper.debugInfo = new Throwable("Connection initial statement");
        }
        return wrapper.connection;
      } catch (Exception e) {
      }
    }
    int newCount = getIncreasingConnectionCount();
    LinkedList list = new LinkedList();
    ConnectionWrapper wrapper = null;
    for (int i = 0; i < newCount; i++) {
      wrapper = getNewConnection();
      if (wrapper != null) {
        list.add(wrapper);
      }
    }
    if (list.size() == 0) {
      return null;
    }
    wrapper = (ConnectionWrapper) list.removeFirst();
    m_usedUsedConnection.add(wrapper);

    m_notUsedConnection.addAll(list);
    list.clear();

    return wrapper.connection;
  }
예제 #13
0
파일: CDatabase.java 프로젝트: tdms/CS6240
  // @SuppressWarnings("unchecked")
  public void checkForOutgoingMessages() throws Exception {
    Statement sqlCmd1, sqlCmd2;
    ResultSet rs;
    LinkedList messageList = new LinkedList();
    COutgoingMessage message;
    int batchLimit;

    batchLimit = settings.getPhoneSettings().getBatchOutgoing();
    sqlCmd1 =
        connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = sqlCmd1.executeQuery("select count(*) as cnt from sms_out where dispatch_date is null");
    rs.next();
    if (rs.getInt("cnt") != 0) {
      rs.close();
      sqlCmd2 = connection.createStatement();
      rs = sqlCmd1.executeQuery("select * from sms_out where dispatch_date is null");
      while (rs.next()) {
        if (messageList.size() > batchLimit) break;
        message =
            new COutgoingMessage(rs.getString("recipient").trim(), rs.getString("text").trim());
        message.setId("" + rs.getInt("id"));
        message.setFlashSms(rs.getInt("flash_sms") == 1);
        message.setStatusReport(rs.getInt("status_report") == 1);
        message.setSourcePort(rs.getInt("src_port"));
        message.setDestinationPort(rs.getInt("dst_port"));
        message.setValidityPeriod(rs.getInt("validity_period"));
        if (settings.getPhoneSettings().getMessageEncoding().equalsIgnoreCase("7bit"))
          message.setMessageEncoding(CMessage.MessageEncoding.Enc7Bit);
        else if (settings.getPhoneSettings().getMessageEncoding().equalsIgnoreCase("8bit"))
          message.setMessageEncoding(CMessage.MessageEncoding.Enc8Bit);
        else if (settings.getPhoneSettings().getMessageEncoding().equalsIgnoreCase("unicode"))
          message.setMessageEncoding(CMessage.MessageEncoding.EncUcs2);
        else message.setMessageEncoding(CMessage.MessageEncoding.Enc7Bit);
        messageList.add(message);
      }
      rs.close();
      mainThread.service.sendMessage(messageList);
      for (int i = 0; i < messageList.size(); i++) {
        message = (COutgoingMessage) messageList.get(i);
        if (message.getDispatchDate() != null) {
          settings.getGeneralSettings().rawOutLog(message);
          if (mainThread.mainWindow != null) {
            mainThread.mainWindow.setOutTo(message.getRecipient());
            mainThread.mainWindow.setOutDate(message.getDispatchDate().toString());
            mainThread.mainWindow.setOutText(message.getText());
          } else {
            System.out.println(CConstants.TEXT_OUTMSG);
            System.out.println("\t" + CConstants.LABEL_OUTGOING_TO + message.getRecipient());
            System.out.println("\t" + CConstants.LABEL_OUTGOING_DATE + message.getDate());
            System.out.println("\t" + CConstants.LABEL_OUTGOING_TEXT + message.getText());
          }
          sqlCmd2.executeUpdate(
              "update sms_out set dispatch_date = "
                  + escapeDate(message.getDispatchDate(), true)
                  + " where id = "
                  + message.getId());
        }
      }
      sqlCmd2.close();
      connection.commit();
    } else {
      rs.close();
      connection.rollback();
    }
    sqlCmd1.close();
  }
  private void initPK(ConnectionProvider cp, String shortTableName)
      throws SQLException, DBException {
    ResultSet rs;

    IndexElement[] iearr = getIndexes();
    if (iearr != null) {
      for (int i = 0; i < iearr.length; i++)
        if (iearr[i].isUnique()) {
          UniqueKeyElementImpl ukei =
              new UniqueKeyElementImpl(
                  iearr[i].getName().getName(),
                  false); // false = not primary key (primary flag is setted later)
          UniqueKeyElement uke = new UniqueKeyElement(ukei, (TableElement) element, iearr[i]);
          uke.setColumns(iearr[i].getColumns());
          changeKeys(new UniqueKeyElement[] {uke}, DBElement.Impl.ADD);
        }

      UniqueKeyElement[] ukes = ((TableElement) element).getUniqueKeys();

      rs =
          cp.getDatabaseMetaData()
              .getPrimaryKeys(cp.getConnection().getCatalog(), cp.getSchema(), shortTableName);

      TreeMap cols = new TreeMap();
      Object keySeq;
      String colName;
      if (rs != null) {
        HashMap rset = new HashMap();
        while (rs.next()) {
          keySeq = rs.getObject("KEY_SEQ"); // NOI18N
          colName = rs.getString("COLUMN_NAME").trim(); // NOI18N

          cols.put(keySeq, colName); // NOI18N
        }
        rs.close();
      }

      boolean primary = false;
      if (cols != null && cols.size() > 0) primary = true;

      if (primary) {
        if (ukes == null || ukes.length == 0) {
          // issue 56492: no index defined for the primary key
          // generate a UniqueKeyElement and an IndexElement for it

          String indexName = "primary_key_index"; // NOI18N
          int i = 1;
          while (((TableElement) element).getIndex(DBIdentifier.create(indexName)) != null) {
            indexName = indexName + i;
            i++;
          }

          LinkedList idxs = new LinkedList();
          for (Iterator it = cols.values().iterator(); it.hasNext(); ) {
            // non-unique = false, thus the index is unique -- see initIndexes()
            idxs.add(indexName + "." + it.next() + ".false"); // NOI18N
          }

          IndexElementImpl iei = new IndexElementImpl(this, indexName, true);
          IndexElement ie = new IndexElement(iei, (TableElement) element);
          iei.initColumns(idxs);
          changeIndexes(new IndexElement[] {ie}, DBElement.Impl.ADD);

          UniqueKeyElementImpl ukei = new UniqueKeyElementImpl(ie.getName().getName(), true);
          UniqueKeyElement uke = new UniqueKeyElement(ukei, (TableElement) element, ie);
          uke.setColumns(ie.getColumns());
          changeKeys(new UniqueKeyElement[] {uke}, DBElement.Impl.ADD);
        } else if (ukes.length == 1) ukes[0].setPrimaryKey(primary);
        else {
          ColumnElement[] ces;
          Object[] o = cols.values().toArray();
          boolean equals;
          for (int i = 0; i < ukes.length; i++) {
            ces = ukes[i].getColumns();
            if (ces.length != o.length) continue;
            else {
              equals = true;
              for (int j = 0; j < ces.length; j++)
                if (!o[j].toString().equals(ces[j].getName().getName())) {
                  equals = false;
                  break;
                }
              if (equals) {
                ukes[i].setPrimaryKey(primary);
                break;
              }
            }
          }
        }
      }
    }
  }
  protected void initIndexes(ConnectionProvider cp, String tbl) {
    if (cp != null)
      try {
        boolean unique;
        DatabaseMetaData dmd = cp.getDatabaseMetaData();
        String shortTableName;
        if (tbl == null) shortTableName = getName().getName();
        else shortTableName = tbl;

        ResultSet rs;
        //                    rs = dmd.getIndexInfo(cp.getConnection().getCatalog(),
        // dmd.getUserName().trim(), shortTableName, false, true);
        rs =
            dmd.getIndexInfo(
                cp.getConnection().getCatalog(), cp.getSchema(), shortTableName, false, true);

        String name, columnName;
        boolean unq;
        LinkedList idxs = new LinkedList();
        if (rs != null) {
          HashMap rset = new HashMap();
          String uniqueStr;
          while (rs.next()) {
            name = rs.getString("INDEX_NAME"); // NOI18N
            columnName = rs.getString("COLUMN_NAME"); // NOI18N
            if (columnName != null) columnName = columnName.trim();
            unq = rs.getBoolean("NON_UNIQUE"); // NOI18N
            // hack for PostgreSQL bug 3480: the driver returns quotes around quoted column names
            if (columnName != null
                && columnName.length() >= 2
                && columnName.startsWith("\"")
                && columnName.endsWith("\"")) { // NOI18N
              columnName = columnName.substring(1, columnName.length() - 1);
            }

            if (name == null) continue;
            else name = name.trim();

            if (unq) idxs.add(name + "." + columnName + ".false"); // NOI18N
            else idxs.add(name + "." + columnName + ".true"); // NOI18N
          }
          rs.close();
        }

        String info;
        int start, end;
        for (int i = 0; i < idxs.size(); i++) {
          info = idxs.get(i).toString();
          start = info.indexOf('.'); // NOI18N
          end = info.lastIndexOf('.'); // NOI18N
          name = info.substring(0, start);
          if ((info.substring(end + 1)).equals("true")) // NOI18N
          unique = true;
          else unique = false;

          if (indexes.find(DBIdentifier.create(name)) != null) continue;

          IndexElementImpl iei = new IndexElementImpl(this, name, unique);
          IndexElement[] ie = {new IndexElement(iei, (TableElement) element)};
          iei.initColumns(idxs);
          changeIndexes(ie, DBElement.Impl.ADD);
        }
      } catch (Exception exc) {
        if (Boolean.getBoolean("netbeans.debug.exceptions")) // NOI18N
        exc.printStackTrace();
      }
  }
예제 #16
0
  public static void main(String[] args) {

    Statement statement = null;
    Connection conn = null;
    ResultSet rsMin = null;

    PreparedStatement psInsert = null;
    LinkedList<Statement> allStatements = new LinkedList<Statement>();

    try {
      // Instantiate the driver
      Class.forName(JDBC_DRIVER);

    } catch (ClassNotFoundException cnfe) {
      System.out.println(
          "Can't instantiate driver class; check you have drives and classpath configured correctly?");
      cnfe.printStackTrace();
      System.exit(-1); // No driver? Need to fix before anything else will work. So quit the program
    }

    try {

      conn = DriverManager.getConnection(DB_CONNECTION_URL, USER, PASSWORD);
      statement = conn.createStatement();
      allStatements.add(statement);

      System.out.println("Average Weather Database Program");

      // Create a table in the database. Stores today's date, and the min and max temperatures
      // recorded.

      String createTableSQL = "CREATE TABLE temp (day date, mintemp double, maxtemp double)";
      String deleteTableSQL = "DROP TABLE temp";
      try {
        statement.executeUpdate(createTableSQL);
        System.out.println("Created temp table");
      } catch (SQLException sqle) {
        // Seems the table already exists. Delete it and recreate it
        if (sqle.getSQLState()
            .startsWith("42")) { // Error code for table already existing start with XO
          System.out.println("Temp table appears to exist already, delete and recreate");
          statement.executeUpdate(deleteTableSQL);
          statement.executeUpdate(createTableSQL);
        } else {
          // Something else went wrong. If we can't create the table, no point attempting
          // to run the rest of the code. Throw the exception again to be handled at the end of the
          // program.
          System.out.println("Got stuck in catch else " + sqle.getSQLState() + " is sql state");
          throw sqle;
        }
      }

      // Add some test data

      String prepStatInsert = "INSERT INTO temp VALUES ( ?, ?, ? )";

      psInsert = conn.prepareStatement(prepStatInsert);
      allStatements.add(psInsert);

      psInsert.setDate(1, Date.valueOf("2014-04-01"));
      psInsert.setDouble(2, 44.2);
      psInsert.setDouble(3, 58.7);
      psInsert.executeUpdate();

      psInsert.setDate(1, Date.valueOf("2014-04-02"));
      psInsert.setDouble(2, 34.6);
      psInsert.setDouble(3, 55.1);
      psInsert.executeUpdate();

      psInsert.setDate(1, Date.valueOf("2014-04-03"));
      psInsert.setDouble(2, 43.9);
      psInsert.setNull(
          3, Types.DOUBLE); // Forgot to record the max temperature for this date so set it to null.
      psInsert.executeUpdate();

      psInsert.setDate(1, Date.valueOf("2014-04-04"));
      psInsert.setDouble(2, 43.8);
      psInsert.setDouble(3, 47.2);
      psInsert.executeUpdate();

      System.out.println("Added test data to database");

      // Let's calculate the average minimum and average maximum temperature for all the days.
      // Add up all the maximum temperatures and divide by number of days to get average max
      // temperature.
      // Add up all the minimum temperatures and divide by number of days to get average min
      // temperature.

      double averageMaxTemp = 0;
      double averageMinTemp = 0;

      String getAvgsSQL = "SELECT AVG(mintemp) AS rsMin, AVG(maxtemp) AS rsMax FROM temp";
      rsMin = statement.executeQuery(getAvgsSQL);
      while (rsMin.next()) { // there is only one
        averageMinTemp = rsMin.getDouble("rsMin");
        System.out.println("Average min is " + averageMinTemp);
        averageMaxTemp = rsMin.getDouble("rsMax");
        System.out.println("Average max is " + averageMaxTemp);
      }

      System.out.println(
          "Average maximum temperature = "
              + averageMaxTemp
              + " , average minimum temperature = "
              + averageMinTemp);

    } catch (SQLException se) {
      se.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // A finally block runs whether an exception is thrown or not. Close resources and tidy up
      // whether this code worked or not.
      try {
        if (rsMin != null) {
          rsMin.close(); // Close result set
          System.out.println("ResultSet closed");
        }
      } catch (SQLException se) {
        se.printStackTrace();
      }

      // Close all of the statements. Stored a reference to each statement in allStatements so we
      // can loop over all of them and close them all.
      for (Statement s : allStatements) {

        if (s != null) {
          try {
            s.close();
            System.out.println("Statement closed");
          } catch (SQLException se) {
            System.out.println("Error closing statement");
            se.printStackTrace();
          }
        }
      }

      try {
        if (conn != null) {
          conn.close(); // Close connection to database
          System.out.println("Database connection closed");
        }
      } catch (SQLException se) {
        se.printStackTrace();
      }
    }

    System.out.println("End of program");
  }