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:PVGraph.java
public java.util.List<PeriodData> getMonthData(int year, int month) { Statement stmt = null;//from www . j a va 2 s. c o m String query = "select * from DayData where year(DateTime) = " + year + " and month(DateTime) = " + month + " and CurrentPower != 0 order by DateTime"; Map<String, PeriodData> result = new HashMap<String, PeriodData>(); GregorianCalendar gc = new GregorianCalendar(); try { getDatabaseConnection(); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String serial = rs.getString("serial"); PeriodData pd = result.get(serial); if (pd == null) { pd = new PeriodData(); pd.serial = serial; pd.inverter = rs.getString("inverter"); pd.startTotalPower = rs.getDouble("ETotalToday"); gc.setTime(rs.getTimestamp("DateTime")); gc.set(Calendar.DAY_OF_MONTH, 1); gc.add(Calendar.MONTH, 1); gc.add(Calendar.DAY_OF_MONTH, -1); pd.numPowers = gc.get(Calendar.DAY_OF_MONTH); result.put(serial, pd); } double power = rs.getDouble("ETotalToday"); gc.setTime(rs.getTimestamp("DateTime")); pd.powers[gc.get(Calendar.DAY_OF_MONTH) - 1] = power; pd.endTotalPower = power; } } catch (SQLException e) { System.err.println("Query failed: " + e.getMessage()); } finally { try { stmt.close(); } catch (SQLException e) { // relax } } return new java.util.ArrayList<PeriodData>(result.values()); }
From source file:dk.netarkivet.harvester.datamodel.HarvestDefinitionDBDAO.java
/** * Get a sparse version of a partial harvest for GUI purposes. * * @param harvestName/*from w w w. j av a 2 s .co m*/ * Name of harvest definition. * @return Sparse version of partial harvest or null for none. * @throws ArgumentNotValid * on null or empty name. */ @Override public SparsePartialHarvest getSparsePartialHarvest(String harvestName) { ArgumentNotValid.checkNotNullOrEmpty(harvestName, "harvestName"); Connection c = HarvestDBConnection.get(); PreparedStatement s = null; try { s = c.prepareStatement("SELECT harvestdefinitions.harvest_id," + " harvestdefinitions.comments," + " harvestdefinitions.numevents," + " harvestdefinitions.submitted," + " harvestdefinitions.isactive," + " harvestdefinitions.edition," + " schedules.name," + " partialharvests.nextdate, " + " harvestdefinitions.audience, " + " harvestdefinitions.channel_id " + "FROM harvestdefinitions, partialharvests, schedules" + " WHERE harvestdefinitions.name = ?" + " AND harvestdefinitions.harvest_id " + "= partialharvests.harvest_id" + " AND schedules.schedule_id " + "= partialharvests.schedule_id"); s.setString(1, harvestName); ResultSet res = s.executeQuery(); if (res.next()) { SparsePartialHarvest sph = new SparsePartialHarvest(res.getLong(1), harvestName, res.getString(2), res.getInt(3), new Date(res.getTimestamp(4).getTime()), res.getBoolean(5), res.getLong(6), res.getString(7), DBUtils.getDateMaybeNull(res, 8), res.getString(9), DBUtils.getLongMaybeNull(res, 10)); sph.setExtendedFieldValues(getExtendedFieldValues(sph.getOid())); return sph; } else { return null; } } catch (SQLException e) { throw new IOFailure("SQL error getting sparse harvest" + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } }
From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java
@Test public void testImportCustomTimeFormatMillisWithTz() throws Exception { methodWatcher.executeUpdate("delete from " + spliceTableWatcher9); PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name "'%s'," + // table name "null," + // insert column list "'%s'," + // file path "null," + // column delimiter "'%s'," + // character delimiter "'yyyy-MM-dd hh:mm:ss.SSSZ'," + // timestamp format "null," + // date format "null," + // time format "%d," + // max bad records "'%s'," + // bad record dir "null," + // has one line records "null)", // char set spliceSchemaWatcher.schemaName, TABLE_9, getResourceDirectory() + "tz_ms_order_date.csv", "\"", 0, BADDIR.getCanonicalPath())); ps.execute();/*from w w w . ja va 2 s.c om*/ ResultSet rs = methodWatcher .executeQuery(format("select * from %s.%s", spliceSchemaWatcher.schemaName, TABLE_9)); List<String> results = Lists.newArrayList(); while (rs.next()) { Timestamp order_date = rs.getTimestamp(1); assertNotNull("order_date incorrect", order_date); //have to deal with differing time zones here SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago")); String textualFormat = sdf.format(order_date); Assert.assertEquals("2013-04-21 09:21:24.980", textualFormat); results.add(String.format("order_date:%s", order_date)); } Assert.assertTrue("import failed!", results.size() == 1); }
From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java
@Test public void testImportCustomTimeFormat() throws Exception { methodWatcher.executeUpdate("delete from " + spliceTableWatcher9); PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name "'%s'," + // table name "null," + // insert column list "'%s'," + // file path "null," + // column delimiter "'%s'," + // character delimiter "'yyyy-MM-dd HH:mm:ssZ'," + // timestamp format "null," + // date format "null," + // time format "%d," + // max bad records "'%s'," + // bad record dir "null," + // has one line records "null)", // char set spliceSchemaWatcher.schemaName, TABLE_9, getResourceDirectory() + "tz_order_date.cs", "\"", 0, BADDIR.getCanonicalPath())); ps.execute();//w w w. j a va2 s. c o m ResultSet rs = methodWatcher .executeQuery(format("select * from %s.%s", spliceSchemaWatcher.schemaName, TABLE_9)); List<String> results = Lists.newArrayList(); while (rs.next()) { Timestamp order_date = rs.getTimestamp(1); assertNotNull("order_date incorrect", order_date); //have to deal with differing time zones here SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago")); String textualFormat = sdf.format(order_date); Assert.assertEquals("2013-06-06 15:02:48.0", textualFormat); results.add(String.format("order_date:%s", order_date)); } Assert.assertTrue("import failed!", results.size() == 1); }
From source file:com.intuit.it.billing.data.BillingDAOImpl.java
/** * @section dao_section class BillingDAOImpl * getAllocation//from ww w . j av a2 s. c o m * * To be used in a caching method where we are pulling all of the allocations at once. The way we can do this * is to merge a date range based set of billing history records with a date range set of allocations. * <p/> * <p/> * <b>DATABASE PROCEDURE:</b> * * @code * FUNCTION fn_get_item_allocations( * item_no IN VARCHAR2 ) * RETURN ref_cursor; * @endcode * <p/> * <b>DATABASE RESULT SET:</b> * <ul> * <li>ALLOCATION_DATE,</li> * <li>ALLOCATION_T, </li> * <li>ALLOCATION_AMT,</li> * <li>AR_ITEM_NO, </li> * <li>BILL_ITEM_NO, </li> * <li>ITEM_DESCRIPTION, </li> * <li>ITEM_CODE,</li> * <li>AR_ITEM_DATE, </li> * <li>BILL_ITEM_DATE </li> * <li>LICENSE</li> * </ul> * * @param customer : The Customer.accountNo account number of the customer who's allocations we need * @param startDate : The starting date of the allocation - to be merged with a billing history record set * @param endDate : The ending date of the allocation - to be merged with a billing history record set * * @return A list of Allocation objects. * @throws JSONException * * * */ @Override public List<Allocation> getAllocation(String itemNo) throws JSONException { List<Allocation> allocs = new ArrayList<Allocation>(); String query = "begin ? := billing_inquiry.fn_get_item_allocations( ? ); end;"; //TODO: configure ResultSet rs = null; Connection conn = null; // DB Connection try { conn = this.getConnection(); } catch (SQLException e) { throw JSONException.sqlError(e); } catch (NamingException e) { throw JSONException.namingError(e.toString()); } try { CallableStatement stmt = conn.prepareCall(query); stmt.registerOutParameter(1, OracleTypes.CURSOR); stmt.setString(2, itemNo); stmt.execute(); rs = (ResultSet) stmt.getObject(1); while (rs.next()) { Allocation a = new Allocation(); a.setAllocatedFromItem(rs.getString("AR_ITEM_NO")); a.setAllocatedToItem(rs.getString("BILL_ITEM_NO")); a.setAllocationAmount(rs.getBigDecimal("ALLOCATION_AMT")); a.setAllocationDate(rs.getTimestamp("ALLOCATION_DATE")); a.setItemCode(rs.getString("ITEM_CODE")); a.setItemDescription(rs.getString("ITEM_DESCRIPTION")); a.setLicense(rs.getString("LICENSE")); allocs.add(a); } conn.close(); rs.close(); } catch (SQLException e) { throw JSONException.sqlError(e); } if (allocs == null || allocs.isEmpty()) { throw JSONException.noDataFound("Null set returned - no data found"); } return allocs; }
From source file:edu.umd.cs.marmoset.modelClasses.Project.java
/** * Populate a Submission from a ResultSet that is positioned * at a row of the submissions table./*from w w w . java 2 s .c o m*/ * * @param resultSet the ResultSet containing the row data * @param startingFrom index specifying where to start fetching attributes from; * useful if the row contains attributes from multiple tables */ public void fetchValues(ResultSet resultSet, int startingFrom) throws SQLException { setProjectPK(Project.asPK(SqlUtilities.getInteger(resultSet, startingFrom++))); setCoursePK(Course.asPK(resultSet.getInt(startingFrom++))); setTestSetupPK(resultSet.getInt(startingFrom++)); setDiffAgainst(Project.asPK(resultSet.getInt(startingFrom++))); setProjectNumber(resultSet.getString(startingFrom++)); setOntime(resultSet.getTimestamp(startingFrom++)); setLate(resultSet.getTimestamp(startingFrom++)); setTitle(resultSet.getString(startingFrom++)); setUrl(resultSet.getString(startingFrom++)); setDescription(resultSet.getString(startingFrom++)); setReleaseTokens(resultSet.getInt(startingFrom++)); setRegenerationTime(resultSet.getInt(startingFrom++)); setIsTested(resultSet.getBoolean(startingFrom++)); setPair(resultSet.getBoolean(startingFrom++)); setVisibleToStudents(resultSet.getBoolean(startingFrom++)); setPostDeadlineOutcomeVisibility(resultSet.getString(startingFrom++)); setKindOfLatePenalty(resultSet.getString(startingFrom++)); setLateMultiplier(resultSet.getDouble(startingFrom++)); setLateConstant(resultSet.getInt(startingFrom++)); setCanonicalStudentRegistrationPK(StudentRegistration.asPK(resultSet.getInt(startingFrom++))); setBestSubmissionPolicy(resultSet.getString(startingFrom++)); setReleasePolicy(resultSet.getString(startingFrom++)); setStackTracePolicy(resultSet.getString(startingFrom++)); // Using -1 to represent infinity int num = resultSet.getInt(startingFrom++); if (num == -1) num = Integer.MAX_VALUE; setNumReleaseTestsRevealed(num); setArchivePK(SqlUtilities.getInteger(resultSet, startingFrom++)); setBrowserEditing(BrowserEditing.valueOfAnyCase(resultSet.getString(startingFrom++))); }
From source file:com.carfinance.module.vehicleservicemanage.domain.VehicleContraceVehsInfoRowMapper.java
public VehicleContraceVehsInfo mapRow(ResultSet rs, int arg1) throws SQLException { VehicleContraceVehsInfo vehicleContraceVehsInfo = new VehicleContraceVehsInfo(); vehicleContraceVehsInfo.setId(rs.getLong("id")); vehicleContraceVehsInfo.setContrace_id(rs.getLong("contrace_id")); vehicleContraceVehsInfo.setVehicle_id(rs.getLong("vehicle_id")); vehicleContraceVehsInfo.setLicense_plate(rs.getString("license_plate")); vehicleContraceVehsInfo.setModel(rs.getString("model")); vehicleContraceVehsInfo.setCompany(rs.getString("company")); vehicleContraceVehsInfo.setIsother(rs.getInt("isother")); vehicleContraceVehsInfo.setDriving_user_id(rs.getLong("driving_user_id")); vehicleContraceVehsInfo.setDriving_user_name(rs.getString("driving_user_name")); vehicleContraceVehsInfo.setDriving_user_license_no(rs.getString("driving_user_license_no")); vehicleContraceVehsInfo.setVehicle_price(rs.getDouble("vehicle_price")); vehicleContraceVehsInfo.setCreate_by(rs.getLong("create_by")); vehicleContraceVehsInfo.setCreate_at(rs.getDate("create_at")); vehicleContraceVehsInfo.setUpdate_by(rs.getLong("update_by")); vehicleContraceVehsInfo.setUpdate_at(rs.getDate("update_at")); try {/* ww w. ja va2 s .com*/ vehicleContraceVehsInfo.setKm(rs.getLong("km")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setOther_vehicle_km(rs.getLong("other_vehicle_km")); } catch (Exception e) { } try { if (rs.getTimestamp("return_time") != null) { String return_time_str = rs.getTimestamp("return_time").toString(); vehicleContraceVehsInfo.setReturn_time(return_time_str.substring(0, return_time_str.length() - 2)); } } catch (Exception e) { } try { vehicleContraceVehsInfo.setReturn_km(rs.getLong("return_km")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setReturn_org(rs.getLong("return_org")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setOver_price(rs.getDouble("over_price")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setStatus(rs.getInt("status")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setEtc(rs.getString("etc")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setEtc_money(rs.getDouble("etc_money")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setOil_percent(rs.getInt("oil_percent")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setRevert_oil_percent(rs.getInt("revert_oil_percent")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setRevert_etc_money(rs.getInt("revert_etc_money")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setDaily_price(rs.getDouble("daily_price")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setSettlement_way(rs.getString("settlement_way")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setFixed_price(rs.getDouble("fixed_price")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setSystem_price(rs.getDouble("system_price")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setReduction_price(rs.getDouble("reduction_price")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setActually_price(rs.getDouble("actually_price")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setTotal_actually(rs.getDouble("total_actually")); } catch (Exception e) { } try { vehicleContraceVehsInfo.setDispatch_status(rs.getInt("dispatch_status")); } catch (Exception e) { } return vehicleContraceVehsInfo; }
From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java
/** * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveMessage(String) */// w ww . j a va2 s . c om public synchronized List<Object> retrieveMessage(final String messageId) throws SQLException { final String methodName = IWebMessagingDAO.CNAME + "#retrieveMessage(final String messageId) throws SQLException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug(messageId); } Connection sqlConn = null; ResultSet resultSet = null; CallableStatement stmt = null; List<Object> svcMessage = null; try { sqlConn = dataSource.getConnection(); if (sqlConn.isClosed()) { throw new SQLException("Unable to obtain application datasource connection"); } sqlConn.setAutoCommit(true); stmt = sqlConn.prepareCall("{CALL retrServiceMessage(?)}"); stmt.setString(1, messageId); if (DEBUG) { DEBUGGER.debug("CallableStatement: {}", stmt); } if (stmt.execute()) { resultSet = stmt.getResultSet(); if (resultSet.next()) { resultSet.first(); svcMessage = new ArrayList<Object>(); svcMessage.add(resultSet.getString(1)); // svc_message_id svcMessage.add(resultSet.getString(2)); // svc_message_title svcMessage.add(resultSet.getString(3)); // svc_message_txt svcMessage.add(resultSet.getString(4)); // svc_message_author svcMessage.add(resultSet.getTimestamp(5)); // svc_message_submitdate svcMessage.add(resultSet.getBoolean(6)); // svc_message_active svcMessage.add(resultSet.getBoolean(7)); // svc_message_alert svcMessage.add(resultSet.getBoolean(8)); // svc_message_expires svcMessage.add(resultSet.getTimestamp(9)); // svc_message_expirydate svcMessage.add(resultSet.getTimestamp(10)); // svc_message_modifiedon svcMessage.add(resultSet.getString(11)); // svc_message_modifiedby if (DEBUG) { DEBUGGER.debug("svcMessage: {}", svcMessage); } } } } catch (SQLException sqx) { ERROR_RECORDER.error(sqx.getMessage(), sqx); throw new SQLException(sqx.getMessage(), sqx); } finally { if (resultSet != null) { resultSet.close(); } if (stmt != null) { stmt.close(); } if ((sqlConn != null) && (!(sqlConn.isClosed()))) { sqlConn.close(); } } return svcMessage; }
From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java
@Test public void testTimestampsWithMillisecondAccuracy() throws Exception { PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name "'%s'," + // table name "null," + // insert column list "'%s'," + // file path "null," + // column delimiter "null," + // character delimiter "'yyyy-MM-dd HH:mm:ss.SSSSSS'," + // timestamp format "null," + // date format "null," + // time format "%d," + // max bad records "'%s'," + // bad record dir "null," + // has one line records "null)", // char set spliceSchemaWatcher.schemaName, TABLE_13, getResourceDirectory() + "datebug.tbl", 0, BADDIR.getCanonicalPath())); ps.execute();/*from w w w .ja v a2 s . co m*/ ResultSet rs = methodWatcher.executeQuery( format("select DW_SRC_EXTRC_DTTM from %s.%s", spliceSchemaWatcher.schemaName, TABLE_13)); int i = 0; while (rs.next()) { i++; Assert.assertNotNull("Timestamp is null", rs.getTimestamp(1)); String ts = rs.getTimestamp(1).toString(); Assert.assertEquals("Microsecond error.", "287469", ts.substring(ts.lastIndexOf('.') + 1)); } Assert.assertEquals("10 Records not imported", 10, i); }
From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java
/** * Convert a <code>ResultSet</code> column into an object. Simple * implementations could just call <code>rs.getObject(index)</code> while * more complex implementations could perform type manipulation to match * the column's type to the bean property type. * * <p>/* w w w.j a v a 2 s.com*/ * This implementation calls the appropriate <code>ResultSet</code> getter * method for the given property type to perform the type conversion. If * the property type doesn't match one of the supported * <code>ResultSet</code> types, <code>getObject</code> is called. * </p> * * @param rs The <code>ResultSet</code> currently being processed. It is * positioned on a valid row before being passed into this method. * * @param index The current column index being processed. * * @param propType The bean property type that this column needs to be * converted into. * * @throws SQLException if a database access error occurs * * @return The object from the <code>ResultSet</code> at the given column * index after optional type processing or <code>null</code> if the column * value was SQL NULL. */ protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException { if (!propType.isPrimitive() && rs.getObject(index) == null) { return null; } if (propType.equals(String.class)) { return rs.getString(index); } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) { return Integer.valueOf(rs.getInt(index)); } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) { return Boolean.valueOf(rs.getBoolean(index)); } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) { return Long.valueOf(rs.getLong(index)); } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) { return Double.valueOf(rs.getDouble(index)); } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) { return Float.valueOf(rs.getFloat(index)); } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) { return Short.valueOf(rs.getShort(index)); } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) { return Byte.valueOf(rs.getByte(index)); } else if (propType.equals(Timestamp.class)) { return rs.getTimestamp(index); } else if (propType.equals(byte[].class)) { return rs.getBytes(index); } else { return rs.getObject(index); } }