List of usage examples for java.sql ResultSet getDate
java.sql.Date getDate(String columnLabel) throws SQLException;
ResultSet
object as a java.sql.Date
object in the Java programming language. From source file:at.alladin.rmbt.statisticServer.UsageJSONResource.java
private JSONObject getClassicUsage(Timestamp begin, Timestamp end) throws SQLException, JSONException { JSONObject returnObj = new JSONObject(); JSONArray sums = new JSONArray(); JSONArray values = new JSONArray(); returnObj.put("sums", sums); returnObj.put("values", values); HashMap<String, Long> fieldSums = new HashMap<>(); fieldSums.put("tests", new Long(0)); fieldSums.put("clients", new Long(0)); fieldSums.put("ips", new Long(0)); PreparedStatement ps;//from w w w .j av a 2s . c om ResultSet rs; final String select = "date_trunc('day', time) _day, count(uid) count_tests, count(DISTINCT client_id) count_clients, count(DISTINCT client_public_ip) count_ips"; final String where = "status='FINISHED' AND deleted=false"; final String sql = "SELECT " + select + " FROM test WHERE " + where + " AND time >= ? AND time < ? GROUP BY _day ORDER BY _day ASC"; ps = conn.prepareStatement(sql); ps.setTimestamp(1, begin); ps.setTimestamp(2, end); rs = ps.executeQuery(); while (rs.next()) { JSONObject entry = new JSONObject(); entry.put("day", rs.getDate("_day").getTime()); JSONArray currentEntryValues = new JSONArray(); entry.put("values", currentEntryValues); JSONObject jTests = new JSONObject(); jTests.put("field", "tests"); jTests.put("value", rs.getLong("count_tests")); currentEntryValues.put(jTests); JSONObject jClients = new JSONObject(); jClients.put("field", "clients"); jClients.put("value", rs.getLong("count_clients")); currentEntryValues.put(jClients); JSONObject jIPs = new JSONObject(); jIPs.put("field", "ips"); jIPs.put("value", rs.getLong("count_ips")); currentEntryValues.put(jIPs); fieldSums.put("tests", fieldSums.get("tests") + rs.getLong("count_tests")); fieldSums.put("clients", fieldSums.get("clients") + rs.getLong("count_clients")); fieldSums.put("ips", fieldSums.get("ips") + rs.getLong("count_ips")); //get some structure in there values.put(entry); } rs.close(); ps.close(); //add field sums for (String field : fieldSums.keySet()) { JSONObject obj = new JSONObject(); obj.put("field", field); obj.put("sum", fieldSums.get(field)); sums.put(obj); } return returnObj; }
From source file:au.com.ish.derbydump.derbydump.metadata.Column.java
/** * Get a string value for the value in this column in the datarow * /*from w ww. jav a2s . c o m*/ * @param dataRow The row which we are exporting * @return an SQL statement compliant string version of the value */ public String toString(ResultSet dataRow) throws SQLException { switch (getColumnDataType()) { case Types.BINARY: case Types.VARBINARY: case Types.BLOB: { Blob obj = dataRow.getBlob(columnName); return (obj == null) ? "NULL" : processBinaryData(obj); } case Types.CLOB: { Clob obj = dataRow.getClob(columnName); return (obj == null) ? "NULL" : processClobData(obj); } case Types.CHAR: case Types.LONGNVARCHAR: case Types.VARCHAR: { String obj = dataRow.getString(columnName); return (obj == null) ? "NULL" : processStringData(obj); } case Types.TIME: { Time obj = dataRow.getTime(columnName); return (obj == null) ? "NULL" : processStringData(obj.toString()); } case Types.DATE: { Date obj = dataRow.getDate(columnName); return (obj == null) ? "NULL" : processStringData(obj.toString()); } case Types.TIMESTAMP: { Timestamp obj = dataRow.getTimestamp(columnName); return (obj == null) ? "NULL" : processStringData(obj.toString()); } case Types.SMALLINT: { Object obj = dataRow.getObject(columnName); return (obj == null) ? "NULL" : obj.toString(); } case Types.BIGINT: { Object obj = dataRow.getObject(columnName); return (obj == null) ? "NULL" : obj.toString(); } case Types.INTEGER: { Object obj = dataRow.getObject(columnName); return (obj == null) ? "NULL" : obj.toString(); } case Types.NUMERIC: case Types.DECIMAL: { BigDecimal obj = dataRow.getBigDecimal(columnName); return (obj == null) ? "NULL" : String.valueOf(obj); } case Types.REAL: case Types.FLOAT: { Float obj = dataRow.getFloat(columnName); // dataRow.getFloat() always returns a value. only way to check the null is wasNull() method return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj); } case Types.DOUBLE: { Double obj = dataRow.getDouble(columnName); return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj); } default: { Object obj = dataRow.getObject(columnName); return (obj == null) ? "NULL" : obj.toString(); } } }
From source file:com.twosigma.beaker.sqlsh.utils.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, NamespaceClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); String sql = queryLine.getResultQuery(); try (Statement statement = conn.createStatement()) { this.statement = statement; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;/*from w ww. ja v a 2s .co m*/ try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { sql = setObject(sql, obj); } else if (!parameter.isArray() && parameter.isObject()) { sql = setObject(sql, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { sql = setObject(sql, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); sql = setObject(sql, arrayElement); } } else { if (obj instanceof List) { sql = setObject(sql, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); sql = setObject(sql, getValue(arrayElement, parameter.getFieldName())); } } } } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(sql); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }
From source file:org.surfnet.cruncher.repository.StatisticsRepositoryImpl.java
/** * {@inheritDoc}/* www. j a va 2 s . c om*/ */ @Override public List<LoginData> getLogins(final LocalDate start, final LocalDate end, final String idpEntityId, final String spEntityId) { final List<LoginData> result = new ArrayList<LoginData>(); NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(cruncherJdbcTemplate); String query = "select * from aggregated_log_logins " + "where " + "entryday >= :startDate AND " + "entryday <= :endDate AND " + "(:spEntityId IS NULL OR spentityid = :spEntityId) AND " + "(:idpEntityId IS NULL OR idpentityid = :idpEntityId) " + "order by idpentityid, spentityid, entryday "; Map<String, Object> parameterMap = getParameterMap(start, end, idpEntityId, spEntityId); namedJdbcTemplate.query(query, parameterMap, new RowMapper<Object>() { private Map<LocalDate, Integer> queryResult = new HashMap<LocalDate, Integer>(); private LoginData currentAggregate = null; @Override public Object mapRow(ResultSet rs, int row) throws SQLException { LoginData currentRow = getLoginDataFromRow(rs); /* * aggregate if sp/idp entityid differs from previous record * do not aggregate if on first record * if on last record, aggregate last entries */ if (!currentRow.equals(currentAggregate) && !rs.isFirst()) { //record is different, aggregate previous one and start fresh result.add(aggregateCurrentEntry(currentAggregate, start, end)); queryResult = new HashMap<LocalDate, Integer>(); } queryResult.put(new LocalDate(rs.getDate("entryday")), rs.getInt("entrycount")); currentAggregate = currentRow; if (rs.isLast()) { // aggregate last set result.add(aggregateCurrentEntry(currentAggregate, start, end)); } /* * This is kinda weird, but single row results are stored in * queryResult (hashmap) or aggregated in result (List<loginData) */ return null; } private LoginData aggregateCurrentEntry(final LoginData loginData, final LocalDate start, final LocalDate end) { LocalDate current = start; int total = 0; while (current.isBefore(end.plusDays(1))) { Integer count = queryResult.get(current); if (count == null) { loginData.getData().add(0); } else { loginData.getData().add(count); total += count; } current = current.plusDays(1); } loginData.setTotal(total); loginData.setPointStart(start.toDate().getTime()); loginData.setPointEnd(end.toDate().getTime()); loginData.setPointInterval(POINT_INTERVAL); return loginData; } private LoginData getLoginDataFromRow(ResultSet rs) throws SQLException { LoginData result = new LoginData(); result.setIdpEntityId(rs.getString("idpentityid")); result.setIdpname(rs.getString("idpentityname")); result.setSpEntityId(rs.getString("spentityid")); result.setSpName(rs.getString("spentityname")); return result; } }); return result; }
From source file:org.obiba.onyx.jade.instrument.gehealthcare.AchillesExpressInstrumentRunner.java
@SuppressWarnings("unchecked") private List<Map<String, Data>> retrieveDeviceData() { log.info("retrieveDeviceData"); return (List<Map<String, Data>>) achillesExpressDb.query( "select assessment, fxrisk, total, tscore, zscore, agematched, percentnormal, sidescanned, stiffnessindex, patients.chart_num, results.SOS, results.BUA, achillesbitmap, appversion, roi_x, roi_y, roi_s, patients.Chart_Num, patients.FName, patients.LName, patients.Sex, patients.DOB from results, patients where results.chart_num = patients.chart_num and patients.chart_num = ?", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, participantID); }/*www.j a v a2 s . c om*/ }, new ResultSetExtractor() { public Object extractData(ResultSet rs) throws SQLException { List<Map<String, Data>> boneDensityDataList = new ArrayList<Map<String, Data>>(); while (rs.next()) { Map<String, Data> boneDensityData = new HashMap<String, Data>(); boneDensityData.put("OUTPUT_PARTICIPANT_BARCODE", DataBuilder.buildText(rs.getString("Chart_Num"))); boneDensityData.put("OUTPUT_PARTICIPANT_FIRST_NAME", DataBuilder.buildText(rs.getString("FName"))); boneDensityData.put("OUTPUT_PARTICIPANT_LAST_NAME", DataBuilder.buildText(rs.getString("LName"))); boneDensityData.put("OUTPUT_PARTICIPANT_DATE_BIRTH", DataBuilder.buildDate(rs.getDate("DOB"))); String gender = rs.getString("Sex").equals("M") ? "MALE" : "FEMALE"; boneDensityData.put("OUTPUT_PARTICIPANT_GENDER", DataBuilder.buildText(gender)); boneDensityData.put("RES_ASSESSMENT", DataBuilder.buildDecimal(rs.getDouble("assessment"))); boneDensityData.put("RES_FRACTURE_RISK", DataBuilder.buildDecimal(rs.getDouble("fxrisk"))); boneDensityData.put("RES_STIFFNESS_INDEX_RES", DataBuilder.buildDecimal(rs.getDouble("total"))); boneDensityData.put("RES_T-SCORE", DataBuilder.buildDecimal(rs.getDouble("tscore"))); boneDensityData.put("RES_Z-SCORE", DataBuilder.buildDecimal(rs.getDouble("zscore"))); boneDensityData.put("RES_PERCENT_AGE_MATCHED", DataBuilder.buildDecimal(rs.getDouble("agematched"))); boneDensityData.put("RES_PERCENT_YOUNG_ADULT", DataBuilder.buildDecimal(rs.getDouble("percentnormal"))); String foot_scanned = rs.getString("sidescanned").equals("L") ? "LEFT_FOOT" : "RIGHT_FOOT"; boneDensityData.put("OUTPUT_FOOT_SCANNED", DataBuilder.buildText(foot_scanned)); boneDensityData.put("RES_STIFFNESS_INDEX", DataBuilder.buildDecimal(rs.getDouble("stiffnessindex"))); boneDensityData.put("RES_SPEED_ULTRASOUND", DataBuilder.buildDecimal(rs.getDouble("SOS"))); boneDensityData.put("RES_BROADBAND_ULTRASOUND_ATT", DataBuilder.buildDecimal(rs.getDouble("BUA"))); boneDensityData.put("RES_SOFTWARE_VERSION", DataBuilder.buildText(rs.getString("appversion"))); boneDensityData.put("RES_REGION_INTERSECTION_X_COOR", DataBuilder.buildInteger(rs.getLong("roi_x"))); boneDensityData.put("RES_REGION_INTERSECTION_Y_COOR", DataBuilder.buildInteger(rs.getLong("roi_y"))); boneDensityData.put("RES_REGION_INTERSECTION_Z_COOR", DataBuilder.buildInteger(rs.getLong("roi_s"))); boneDensityData.put("RES_STIFFNESS_INDEX_GRAPH", DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap"))); boneDensityDataList.add(boneDensityData); } return boneDensityDataList; } }); }
From source file:edu.clemson.cs.nestbed.server.adaptation.sql.MoteTypeSqlAdapter.java
public Map<Integer, MoteType> readMoteTypes() throws AdaptationException { Map<Integer, MoteType> moteTypes = new HashMap<Integer, MoteType>(); Connection connection = null; Statement statement = null;//w ww.j av a 2 s. c o m ResultSet resultSet = null; try { String query = "SELECT * FROM MoteTypes"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); while (resultSet.next()) { int id; String name; int totalROM; int totalRAM; int totalEEPROM; Blob imageBlob; String tosPlatform; Date timestamp; id = resultSet.getInt(Index.ID.index()); name = resultSet.getString(Index.NAME.index()); totalROM = resultSet.getInt(Index.TOTALROM.index()); totalRAM = resultSet.getInt(Index.TOTALRAM.index()); totalEEPROM = resultSet.getInt(Index.TOTALEEPROM.index()); imageBlob = resultSet.getBlob(Index.IMAGE.index()); tosPlatform = resultSet.getString(Index.TOSPLATFORM.index()); timestamp = resultSet.getDate(Index.TIMESTAMP.index()); byte[] image = (imageBlob != null && imageBlob.length() > 0) ? imageBlob.getBytes(1, (int) imageBlob.length()) : null; MoteType moteType = MoteType.getMoteType(id, name, totalROM, totalRAM, totalEEPROM, image, tosPlatform, timestamp); moteTypes.put(id, moteType); } } catch (SQLException ex) { String msg = "SQLException in readMoteTypes"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return moteTypes; }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.UUIDDAOImpl.java
private ParameterizedRowMapper<UUIDDetail> getUUIDRowMapper() { return new ParameterizedRowMapper<UUIDDetail>() { public UUIDDetail mapRow(final ResultSet resultSet, final int rowNum) throws SQLException { UUIDDetail uuidDetail = new UUIDDetail(); uuidDetail.setUuid(resultSet.getString("UUID")); uuidDetail.setCreatedBy(resultSet.getString("CREATED_BY")); uuidDetail.setCenter(getCenter(resultSet.getInt("CENTER_ID"), resultSet.getString("DOMAIN_NAME"), resultSet.getString("CENTER_TYPE_CODE"))); uuidDetail.setCreationDate(resultSet.getDate("CREATE_DATE")); uuidDetail.setGenerationMethod( UUIDConstants.getGenerationMethod(resultSet.getInt("GENERATION_METHOD_ID"))); uuidDetail.setLatestBarcode(resultSet.getString("BARCODE")); uuidDetail.setDiseaseAbbrev(resultSet.getString("DISEASE_ABBREVIATION")); return uuidDetail; }//w ww . j a v a2s. c o m }; }
From source file:com.trackplus.ddl.GenericStringValueConverter.java
protected String extractColumnValue(ResultSet resultSet, int columnIdx, int jdbcType) throws SQLException, DDLException { String value = resultSet.getString(columnIdx); if (value != null) { switch (jdbcType) { case Types.NUMERIC: case Types.DECIMAL: break; case Types.BIT: case Types.BOOLEAN: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: case Types.REAL: case Types.FLOAT: case Types.DOUBLE: { break; }//from w ww . j av a2 s. c o m case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.BINARY: case Types.VARBINARY: case Types.TIME: case Types.CLOB: case Types.ARRAY: case Types.REF: { value = "'" + value.replaceAll("'", "''") + "'"; break; } case Types.DATE: case Types.TIMESTAMP: { Date d = resultSet.getDate(columnIdx); Calendar cal = Calendar.getInstance(); cal.setTime(d); int year = cal.get(Calendar.YEAR); if (year < 1900) { throw new DDLException("Invalid date:" + d); } else { value = "'" + value + "'"; } break; } case Types.BLOB: case Types.LONGVARBINARY: { Blob blobValue = resultSet.getBlob(columnIdx); String str = new String(Base64.encodeBase64(blobValue.getBytes(1l, (int) blobValue.length()))); value = "'" + str + "'"; break; } default: break; } } return value; }
From source file:org.apache.drill.test.framework.Utils.java
public static String getSqlResult(ResultSet resultSet) throws SQLException { StringBuffer stringBuffer = new StringBuffer(); List columnLabels = new ArrayList<String>(); try {/*w w w . ja va 2 s . c o m*/ int columnCount = resultSet.getMetaData().getColumnCount(); for (int i = 1; i <= columnCount; i++) { columnLabels.add(resultSet.getMetaData().getColumnLabel(i)); } List<Integer> types = Lists.newArrayList(); for (int i = 1; i <= columnCount; i++) { types.add(resultSet.getMetaData().getColumnType(i)); } LOG.debug("Result set data types:"); LOG.debug(Utils.getTypesInStrings(types)); stringBuffer.append(new ColumnList(types, columnLabels).toString() + "\n"); while (resultSet.next()) { List<Object> values = Lists.newArrayList(); for (int i = 1; i <= columnCount; i++) { try { if (resultSet.getObject(i) == null) { values.add(null); continue; } if (resultSet.getMetaData().getColumnType(i) == Types.NVARCHAR) { values.add(new String(resultSet.getBytes(i), "UTF-16")); } else { values.add(new String(resultSet.getBytes(i), "UTF-8")); } } catch (Exception e) { if (resultSet.getMetaData().getColumnType(i) == Types.DATE) { values.add(resultSet.getDate(i)); } else { values.add(resultSet.getObject(i)); } } } stringBuffer.append(new ColumnList(types, values).toString() + "\n"); } } catch (IllegalArgumentException | IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if (resultSet != null) { resultSet.close(); } } return stringBuffer.toString(); }
From source file:com.skilrock.lms.coreEngine.accMgmt.common.SearchChequeHelper.java
/** * This method is used to search cheque which submitted by the retailer * //from w ww.ja va 2 s . co m * @param searchMap * @return * @throws LMSException */ public List searchChequeRetailer(Map searchMap, int agent_id, double chequeBounceCharge) throws LMSException { Connection connection = null; Statement statement = null; ResultSet resultSet = null; logger.debug("-----Query----::"); try { ChequeBean chequeBean = null; List<ChequeBean> searchResults = new ArrayList<ChequeBean>(); connection = DBConnect.getConnection(); statement = connection.createStatement(); String dynamicWhereClause = getWhereClauseForRetailer(searchMap); String query = QueryManager.getST5ChequeSearchRetailerQuery() + "and agent_user_id=" + agent_id + "" + dynamicWhereClause; logger.debug("-----Query----::" + query); resultSet = statement.executeQuery(query); while (resultSet.next()) { chequeBean = new ChequeBean(); logger.debug("-----Query----::"); chequeBean.setChequeNumber(resultSet.getString("cheque_nbr")); chequeBean.setChequeDate(resultSet.getDate(TableConstants.CHEQUE_DATE).toString()); chequeBean.setIssuePartyname(resultSet.getString(TableConstants.ISSUE_PARTY_NAME)); chequeBean.setBankName(resultSet.getString(TableConstants.DRAWEE_BANK)); chequeBean.setChequeAmount(resultSet.getDouble(TableConstants.CHEQUE_AMT)); chequeBean.setOrgName(resultSet.getString(TableConstants.NAME)); chequeBean.setTransactionId(resultSet.getLong(TableConstants.TRANSACTION_ID)); // chequeBean.setChequeBounceCharges(chequeBounceCharge); searchResults.add(chequeBean); logger.debug("Cheque Number" + resultSet.getString("cheque_nbr")); logger.debug("Org Name:" + resultSet.getString(TableConstants.NAME)); logger.debug("Bank" + resultSet.getString(TableConstants.DRAWEE_BANK)); } return searchResults; } catch (SQLException e) { logger.error("Exception: " + e); e.printStackTrace(); throw new LMSException(e); } finally { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException se) { logger.error("Exception: " + se); throw new LMSException(se); } } }