List of usage examples for java.sql ResultSet getTimestamp
java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;
ResultSet
object as a java.sql.Timestamp
object in the Java programming language. From source file:se.technipelago.weather.chart.Generator.java
private void setArchivedData(Map<String, Object> map) { PreparedStatement stmt = null; ResultSet result = null; init();/* ww w . j a v a 2s .c o m*/ try { stmt = conn.prepareStatement("SELECT * FROM archive WHERE ts = (SELECT MAX(ts) FROM archive)"); result = stmt.executeQuery(); if (result.next()) { map.put("timestamp", result.getTimestamp(2)); map.put("temp_out", result.getFloat(3)); map.put("temp_in", result.getFloat(4)); map.put("hum_out", result.getInt(5)); map.put("hum_in", result.getInt(6)); map.put("dew", calculateDewPoint(result.getFloat(3), result.getInt(5))); map.put("heat_index", calculateHeatIndex(result.getFloat(3), result.getInt(5))); map.put("barometer", result.getFloat(7)); map.put("rain", result.getFloat(8)); map.put("rain_rate", result.getFloat(9)); map.put("wind_avg", result.getFloat(10)); map.put("wind_dir", getDirection(result.getInt(11))); map.put("wind_dir_name", getDirectionName(result.getInt(11))); map.put("wind_high", result.getFloat(12)); map.put("chill", calculateWindChill(result.getFloat(3), result.getFloat(10))); map.put("solar", result.getInt(13)); map.put("uv", result.getFloat(14)); } } catch (SQLException ex) { log.log(Level.SEVERE, null, ex); } finally { if (result != null) { try { result.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close ResultSet", ex); } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close select statement", ex); } } } }
From source file:dao.DirSearchQuery.java
/** * This method lists all the results for the search text from directories * @param conn the connection/*from w ww.j a v a 2s . com*/ * @param collabrumId the collabrumid * @return HashSet the set that has the list of moderators for these collabrums. * @throws BaseDaoException - when error occurs **/ public HashSet run(Connection conn, String stext) throws BaseDaoException { if ((RegexStrUtil.isNull(stext) || conn == null)) { return null; } ResultSet rs = null; StringBuffer sb = new StringBuffer( "select distinct directoryid, dirname, LEFT(dirdesc, 160) as info, hits, creationdate from directory where "); ArrayList columns = new ArrayList(); columns.add("dirdesc"); columns.add("dirname"); columns.add("keywords"); sb.append(sqlSearch.getConstraint(columns, stext)); sb.append(" order by hits DESC"); logger.info("search = " + sb.toString()); try { PreparedStatement stmt = conn.prepareStatement(sb.toString()); rs = stmt.executeQuery(); Vector columnNames = null; Directory directory = null; HashSet pendingSet = new HashSet(); if (rs != null) { columnNames = dbutils.getColumnNames(rs); } else { return null; } while (rs.next()) { directory = (Directory) eop.newObject(DbConstants.DIRECTORY); for (int j = 0; j < columnNames.size(); j++) { if (((String) (columnNames.elementAt(j))).equalsIgnoreCase("creationdate")) { try { directory.setValue("creationdate", GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp("creationdate"))); } catch (ParseException e) { throw new BaseDaoException( "could not parse the date for creationdate in DirSearchQuery()" + rs.getTimestamp("creationdate"), e); } } else { directory.setValue((String) columnNames.elementAt(j), (String) rs.getString((String) columnNames.elementAt(j))); } } pendingSet.add(directory); } return pendingSet; } catch (Exception e) { throw new BaseDaoException("Error occured while executing search in directory run query ", e); } }
From source file:com.googlecode.fascinator.portal.HouseKeeper.java
/** * Rebuild the in-memory list of actions from the database. * //from w w w. j a v a 2 s.c o m */ private void syncActionList() { // Purge current list actions = new ArrayList<UserAction>(); try { // Prepare our query PreparedStatement sql = dbConnection() .prepareCall("SELECT * FROM " + NOTIFICATIONS_TABLE + " ORDER BY block DESC, id"); // Run the query ResultSet result = sql.executeQuery(); // Build our list while (result.next()) { UserAction ua = new UserAction(); ua.id = result.getInt("id"); ua.block = result.getBoolean("block"); ua.message = result.getString("message"); ua.date = new Date(result.getTimestamp("datetime").getTime()); actions.add(ua); } // Release the resultset close(result); close(sql); } catch (SQLException ex) { log.error("Error accessing database: ", ex); } }
From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java
/** * Retrieve a JDBC column value from a ResultSet, using the specified value type. * <p>Uses the specifically typed ResultSet accessor methods, falling back to * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types. * <p>Note that the returned value may not be assignable to the specified * required type, in case of an unknown type. Calling code needs to deal * with this case appropriately, e.g. throwing a corresponding exception. * @param rs is the ResultSet holding the data * @param index is the column index//from w w w .j a v a2 s . co m * @param requiredType the required value type (may be <code>null</code>) * @return the value object * @throws SQLException if thrown by the JDBC API */ public static Object getResultSetValue(ResultSet rs, int index, Class requiredType) throws SQLException { if (requiredType == null) { return getResultSetValue(rs, index); } Object value = null; boolean wasNullCheck = false; // Explicitly extract typed value, as far as possible. if (String.class.equals(requiredType)) { value = rs.getString(index); } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) { value = Boolean.valueOf(rs.getBoolean(index)); wasNullCheck = true; } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) { value = Byte.valueOf(rs.getByte(index)); wasNullCheck = true; } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) { value = Short.valueOf(rs.getShort(index)); wasNullCheck = true; } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) { value = Integer.valueOf(rs.getInt(index)); wasNullCheck = true; } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) { value = Long.valueOf(rs.getLong(index)); wasNullCheck = true; } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) { value = Float.valueOf(rs.getFloat(index)); wasNullCheck = true; } else if (double.class.equals(requiredType) || Double.class.equals(requiredType) || Number.class.equals(requiredType)) { value = Double.valueOf(rs.getDouble(index)); wasNullCheck = true; } else if (byte[].class.equals(requiredType)) { value = rs.getBytes(index); } else if (java.sql.Date.class.equals(requiredType)) { value = rs.getDate(index); } else if (java.sql.Time.class.equals(requiredType)) { value = rs.getTime(index); } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) { value = rs.getTimestamp(index); } else if (BigDecimal.class.equals(requiredType)) { value = rs.getBigDecimal(index); } else if (Blob.class.equals(requiredType)) { value = rs.getBlob(index); } else if (Clob.class.equals(requiredType)) { value = rs.getClob(index); } else { // Some unknown type desired -> rely on getObject. value = getResultSetValue(rs, index); } // Perform was-null check if demanded (for results that the // JDBC driver returns as primitives). if (wasNullCheck && value != null && rs.wasNull()) { value = null; } return value; }
From source file:com.sfs.whichdoctor.dao.OnlineApplicationDAOImpl.java
/** * Load online application bean.//from w ww .j av a2 s . c o m * * @param rs the result set * * @return the online application bean * * @throws SQLException the SQL exception */ private OnlineApplicationBean loadOnlineApplicationBean(final ResultSet rs) throws SQLException { OnlineApplicationBean onlineApplication = new OnlineApplicationBean(); onlineApplication.setId(rs.getInt("OnlineApplicationId")); onlineApplication.setKey(rs.getString("ApplicationKey")); onlineApplication.setFirstName(rs.getString("FirstName")); onlineApplication.setLastName(rs.getString("LastName")); onlineApplication.setPersonGUID(rs.getInt("PersonGUID")); onlineApplication.setApplicationXml(rs.getString("ApplicationXML")); onlineApplication.setStatus(rs.getString("Status")); onlineApplication.setRecordNumber(rs.getString("RecordNumber")); onlineApplication.setType(rs.getString("Type")); onlineApplication.setProcessed(rs.getBoolean("Processed")); try { onlineApplication.setCreatedDate(rs.getTimestamp("Created")); } catch (SQLException e) { dataLogger.debug("Error reading Created date: " + e.getMessage()); } try { onlineApplication.setModifiedDate(rs.getTimestamp("Modified")); } catch (SQLException e) { dataLogger.debug("Error reading Modified date: " + e.getMessage()); } if (!onlineApplication.getProcessed() && onlineApplication.getPersonGUID() == 0 && StringUtils.equals(onlineApplication.getStatus(), "Unprocessed")) { // Check to see if a relevant person already exists try { onlineApplication.setExistingRecord(this.getExistingRecord(onlineApplication)); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error searching for an existing person: " + wde.getMessage()); } } return onlineApplication; }
From source file:com.sfs.whichdoctor.dao.ExpenseClaimDAOImpl.java
/** * Load expense claim.//from w w w . ja v a 2 s .com * * @param rs the rs * @return the expense claim bean * @throws SQLException the sQL exception */ private ExpenseClaimBean loadExpenseClaim(final ResultSet rs) throws SQLException { ExpenseClaimBean expenseClaim = new ExpenseClaimBean(); expenseClaim.setId(rs.getInt("ExpenseClaimId")); expenseClaim.setGUID(rs.getInt("GUID")); expenseClaim.setReferenceGUID(rs.getInt("ReferenceGUID")); expenseClaim.setExpenseClass(rs.getString("ExpenseClass")); expenseClaim.setExpenseType(rs.getString("ExpenseType")); expenseClaim.setCurrencyAbbreviation(rs.getString("CurrencyAbbreviation")); try { expenseClaim.setExpenseDate(rs.getDate("ExpenseDate")); } catch (SQLException sqe) { dataLogger.debug("Error loading ExpenseDate: " + sqe.getMessage()); } expenseClaim.setExchangeRate(rs.getDouble("ExchangeRate")); expenseClaim.setDescription(rs.getString("Description")); expenseClaim.setRate(rs.getDouble("Rate")); expenseClaim.setQuantity(rs.getInt("Quantity")); expenseClaim.setGSTRate(rs.getDouble("GSTRate")); expenseClaim.setValue(rs.getDouble("Value")); expenseClaim.setNetValue(rs.getDouble("NetValue")); expenseClaim.setActive(rs.getBoolean("Active")); try { expenseClaim.setCreatedDate(rs.getTimestamp("CreatedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage()); } expenseClaim.setCreatedBy(rs.getString("CreatedBy")); try { expenseClaim.setModifiedDate(rs.getTimestamp("ModifiedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage()); } expenseClaim.setModifiedBy(rs.getString("ModifiedBy")); return expenseClaim; }
From source file:dsd.dao.ParametersDAO.java
public static List<Parameter> GetValidParameters(Calendar cal) { try {//from w w w. j a va 2 s . c o m Connection con = DAOProvider.getDataSource().getConnection(); ArrayList<Parameter> parametersList = new ArrayList<Parameter>(); try { Object[] parameters = new Object[1]; parameters[0] = new Timestamp(cal.getTimeInMillis()); ResultSet results = DAOProvider.SelectTableSecure( // table part tableNameParameters + " join " + tableNameParameterData + " on " + tableNameParameters + ".ID = " + tableNameParameterData + "." + tableParameterDataFields[0], // select part tableNameParameterData + "." + "ID" + " as " + tableNameParameterData + "_" + "ID" + ", " + tableNameParameterData + "." + tableParameterDataFields[0] + " as " + tableNameParameterData + "_" + tableParameterDataFields[0] + ", " + tableNameParameterData + "." + tableParameterDataFields[1] + " as " + tableNameParameterData + "_" + tableParameterDataFields[1] + ", " + tableNameParameterData + "." + tableParameterDataFields[2] + " as " + tableNameParameterData + "_" + tableParameterDataFields[2] + ", " + tableNameParameterData + "." + tableParameterDataFields[3] + " as " + tableNameParameterData + "_" + tableParameterDataFields[3] + ", " + "parameters.* ", // where part " (parameters_id, timestamp) in (select parameters_id, max(timestamp) " + " from parameter_data " + " where timestamp < ? " + " group by parameters_id " + "); ", // order by part "", con, parameters); while (results.next()) { Parameter parameter = new Parameter(); parameter.setParameterID(results.getLong("ID")); parameter.setAbbreviation(results.getString(tableParametersFields[1])); parameter.setCategory( eParameterCategory.getParameterCategory(results.getInt(tableParametersFields[4]))); parameter.setName(results.getString(tableParametersFields[0])); parameter.setParameterDataID(results.getLong(tableNameParameterData + "_ID")); parameter.setTimestamp(results .getTimestamp(tableNameParameterData + "_" + tableParameterDataFields[3]).getTime()); parameter.setUnit(results.getString(tableParametersFields[2])); parameter.setUserID(results.getInt(tableNameParameterData + "_" + tableParameterDataFields[2])); parameter .setValue(results.getFloat(tableNameParameterData + "_" + tableParameterDataFields[1])); parametersList.add(parameter); } } catch (Exception exc) { exc.printStackTrace(); } con.close(); return parametersList; } catch (Exception exc) { exc.printStackTrace(); } return null; }
From source file:gov.nih.nci.cadsr.persist.de.Data_Elements_Mgr.java
/** * Returns DE based on the de_IDSEQ//from w w w. j av a 2s . co m * * @param de_IDSEQ * @param conn * @return * @throws DBException */ public DeVO getDe(String de_IDSEQ, Connection conn) throws DBException { PreparedStatement stmt = null; ResultSet rs = null; DeVO deVO = null; try { String sql = "select * from data_elements_view where de_idseq = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, de_IDSEQ); rs = stmt.executeQuery(); while (rs.next()) { deVO = new DeVO(); deVO.setDe_IDSEQ(rs.getString("DE_IDSEQ")); deVO.setVersion(rs.getDouble("VERSION")); deVO.setConte_IDSEQ(rs.getString("CONTE_IDSEQ")); deVO.setPrefferred_name(rs.getString("PREFERRED_NAME")); deVO.setVd_IDSEQ(rs.getString("VD_IDSEQ")); deVO.setDec_IDSEQ(rs.getString("DEC_IDSEQ")); deVO.setPrefferred_def(rs.getString("PREFERRED_DEFINITION")); deVO.setAsl_name(rs.getString("ASL_NAME")); deVO.setLong_name(rs.getString("LONG_NAME")); deVO.setLastest_version_ind(rs.getString("LATEST_VERSION_IND")); deVO.setDeleted_ind(rs.getString("DELETED_IND")); deVO.setDate_created(rs.getTimestamp("DATE_CREATED")); deVO.setBegin_date(rs.getTimestamp("BEGIN_DATE")); deVO.setCreated_by(rs.getString("CREATED_BY")); deVO.setEnd_date(rs.getTimestamp("END_DATE")); deVO.setDate_modified(rs.getTimestamp("DATE_MODIFIED")); deVO.setModified_by(rs.getString("MODIFIED_BY")); deVO.setChange_note(rs.getString("CHANGE_NOTE")); } } catch (SQLException e) { logger.error(DBException.DEFAULT_ERROR_MSG + " in getDe() method of Data_Elements_Mgr class " + e); throw new DBException("API_DE_000"); } finally { try { rs = SQLHelper.closeResultSet(rs); stmt = SQLHelper.closePreparedStatement(stmt); } catch (Exception e) { } } return deVO; }
From source file:eionet.meta.dao.mysql.VocabularyFolderDAOImpl.java
/** * {@inheritDoc}/*from ww w . j a v a 2 s. co m*/ */ @Override public List<VocabularyFolder> getWorkingCopies(String userName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("workingUser", userName); StringBuilder sql = new StringBuilder(); sql.append( "select v.VOCABULARY_ID, v.IDENTIFIER, v.LABEL, v.REG_STATUS, v.WORKING_COPY, v.BASE_URI, v.VOCABULARY_TYPE, "); sql.append("v.WORKING_USER, v.DATE_MODIFIED, v.USER_MODIFIED, v.CHECKEDOUT_COPY_ID, v.CONTINUITY_ID, "); sql.append("v.CONCEPT_IDENTIFIER_NUMERIC, "); sql.append("f.ID, f.IDENTIFIER, f.LABEL "); sql.append("from VOCABULARY v "); sql.append("left join VOCABULARY_SET f on f.ID=v.FOLDER_ID "); sql.append("where v.WORKING_USER=:workingUser and v.WORKING_COPY = 1"); List<VocabularyFolder> items = getNamedParameterJdbcTemplate().query(sql.toString(), params, new RowMapper<VocabularyFolder>() { @Override public VocabularyFolder mapRow(ResultSet rs, int rowNum) throws SQLException { VocabularyFolder vf = new VocabularyFolder(); vf.setId(rs.getInt("v.VOCABULARY_ID")); vf.setIdentifier(rs.getString("v.IDENTIFIER")); vf.setLabel(rs.getString("v.LABEL")); vf.setRegStatus(RegStatus.fromString(rs.getString("v.REG_STATUS"))); vf.setType(VocabularyType.valueOf(rs.getString("v.VOCABULARY_TYPE"))); vf.setWorkingCopy(rs.getBoolean("v.WORKING_COPY")); vf.setWorkingUser(rs.getString("v.WORKING_USER")); vf.setDateModified(rs.getTimestamp("v.DATE_MODIFIED")); vf.setUserModified(rs.getString("v.USER_MODIFIED")); vf.setCheckedOutCopyId(rs.getInt("v.CHECKEDOUT_COPY_ID")); vf.setFolderName(rs.getString("f.IDENTIFIER")); vf.setFolderId(rs.getInt("f.ID")); vf.setFolderLabel(rs.getString("f.LABEL")); return vf; } }); return items; }
From source file:org.mayocat.accounts.store.jdbi.mapper.TenantMapper.java
@Override public Tenant map(int index, ResultSet result, StatementContext statementContext) throws SQLException { String slug = result.getString("slug"); String defaultHost = result.getString("default_host"); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new GuavaModule()); Integer configurationVersion = result.getInt("configuration_version"); TenantConfiguration configuration;//from ww w. ja va 2 s . co m if (Strings.isNullOrEmpty(result.getString("configuration"))) { configuration = new TenantConfiguration(configurationVersion, Collections.<String, Serializable>emptyMap()); } else { try { Map<String, Serializable> data = mapper.readValue(result.getString("configuration"), new TypeReference<Map<String, Object>>() { }); configuration = new TenantConfiguration(configurationVersion, data); } catch (IOException e) { final Logger logger = LoggerFactory.getLogger(TenantMapper.class); logger.error("Failed to load configuration for tenant with slug [{}]", e); configuration = new TenantConfiguration(); } } Tenant tenant = new Tenant((UUID) result.getObject("id"), slug, configuration); tenant.setFeaturedImageId((UUID) result.getObject("featured_image_id")); tenant.setSlug(slug); tenant.setDefaultHost(defaultHost); tenant.setCreationDate(result.getTimestamp("creation_date")); tenant.setName(result.getString("name")); tenant.setDescription(result.getString("description")); tenant.setContactEmail(result.getString("contact_email")); return tenant; }