Example usage for java.sql PreparedStatement setTimestamp

List of usage examples for java.sql PreparedStatement setTimestamp

Introduction

In this page you can find the example usage for java.sql PreparedStatement setTimestamp.

Prototype

void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.sql.Timestamp value.

Usage

From source file:com.wabacus.system.datatype.CTimestampType.java

public void setPreparedStatementValue(int index, Date dateValue, PreparedStatement pstmt) throws SQLException {
    log.debug("setTimestamp(" + index + "," + dateValue + ")");
    if (dateValue == null) {
        pstmt.setTimestamp(index, null);
    } else {// w  ww.j  ava 2  s .  com
        pstmt.setTimestamp(index, new java.sql.Timestamp(dateValue.getTime()));
    }
}

From source file:com.recomdata.grails.rositaui.etl.dao.ValidationErrorBatchPreparedStatementSetter.java

@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
    ValidationError v = items.get(i);/*ww  w  .j  av a2 s .c  o  m*/
    ps.setString(1, v.getType());
    ps.setLong(2, v.getLineNumber());
    ps.setString(3, v.getMessage());
    ps.setTimestamp(4, new Timestamp(v.getDate().getTime()));
    ps.setString(5, v.getSchema());
    ps.setString(6, v.getLocation());
    ps.setString(7, v.getSourceType());
    ps.setString(8, v.getFilename());
}

From source file:com.aurel.track.dbase.MigrateTo37.java

private static void addHistoryTransaction(PreparedStatement pstmtHistoryTransaction, int transactionID,
        Integer workItemID, Integer changedBy, Date lastEdit) {
    try {/*from w w w  .  j a v a2s.  c  o m*/
        pstmtHistoryTransaction.setInt(1, transactionID);
        pstmtHistoryTransaction.setInt(2, workItemID);
        pstmtHistoryTransaction.setInt(3, changedBy);
        if (lastEdit == null) {
            pstmtHistoryTransaction.setDate(4, null);
        } else {
            pstmtHistoryTransaction.setTimestamp(4, new java.sql.Timestamp(lastEdit.getTime()));
        }
        pstmtHistoryTransaction.setString(5, UUID.randomUUID().toString());
        pstmtHistoryTransaction.executeUpdate();
    } catch (Exception e) {
        LOGGER.error("Adding a transaction  with transactionID " + transactionID + " workItemID " + workItemID
                + " changedBy " + changedBy + " at " + lastEdit + " failed with " + e.getMessage(), e);
        System.err.println(ExceptionUtils.getStackTrace(e));
    }
}

From source file:net.freechoice.dao.impl.Dao_Transaction.java

@Override
public List<FC_Transaction> getTransactionsOnTime(final Timestamp timestamp) {

    return getJdbcTemplate().query(new PreparedStatementCreator() {
        @Override//w  ww .  j a va  2 s.c  om
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {

            PreparedStatement ps = con.prepareStatement(SELECT_FROM_FC_TRANSACTION
                    + "where is_valid = true and time_committed = ?" + Dao_Transaction.TIME_DESCEND);
            ps.setTimestamp(1, timestamp);
            return ps;
        }
    }, mapper);
}

From source file:net.mindengine.oculus.frontend.service.report.filter.JdbcFilterDAO.java

@Override
public long createFilter(Filter filter) throws Exception {
    String sql = "insert into filters (name, description, user_id, date, filter) values (?,?,?,?,?)";
    PreparedStatement ps = getConnection().prepareStatement(sql);

    ps.setString(1, filter.getName());//from w  ww. j av a2 s . c o  m
    ps.setString(2, filter.getDescription());
    ps.setLong(3, filter.getUserId());
    ps.setTimestamp(4, new Timestamp(filter.getDate().getTime()));
    ps.setString(5, filter.getFilter());

    logger.info(ps);
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return 0;
}

From source file:com.jernejerin.traffic.helper.TripOperations.java

/**
 * Insert a trip into database./*from   w w w  . j  a  v  a 2s  .c  o  m*/
 *
 * @param trip trip to insert.
 * @param table table into which we need to insert trip
 */
public static void insertTrip(Trip trip, String table) {
    //        LOGGER.log(Level.INFO, "Started inserting trip into DB for trip = " +
    //                trip.toString() + " from thread = " + Thread.currentThread());
    PreparedStatement insertTrip = null;
    Connection conn = null;
    try {
        // first we need to get connection from connection pool
        conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:taxi");

        // setting up prepared statement
        insertTrip = conn.prepareStatement("insert into " + table
                + " (eventId, medallion, hack_license, pickup_datetime, "
                + "dropoff_datetime, trip_time, trip_distance, pickup_longitude, pickup_latitude, dropoff_longitude, "
                + "dropoff_latitude, payment_type, fare_amount, surcharge, mta_tax, tip_amount, tolls_amount, "
                + "total_amount, timestampReceived) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        insertTrip.setInt(1, trip.getId());
        insertTrip.setString(2, trip.getMedallion());
        insertTrip.setString(3, trip.getHackLicense());
        insertTrip.setTimestamp(4,
                new Timestamp(trip.getPickupDatetime().toEpochSecond(ZoneOffset.UTC) * 1000));
        insertTrip.setTimestamp(5,
                new Timestamp(trip.getDropOffDatetime().toEpochSecond(ZoneOffset.UTC) * 1000));
        insertTrip.setInt(6, trip.getTripTime());
        insertTrip.setDouble(7, trip.getTripDistance());
        insertTrip.setDouble(8, trip.getPickupLongitude());
        insertTrip.setDouble(9, trip.getPickupLatitude());
        insertTrip.setDouble(10, trip.getDropOffLongitude());
        insertTrip.setDouble(11, trip.getDropOffLatitude());
        insertTrip.setString(12, trip.getPaymentType() != null ? trip.getPaymentType().name() : null);
        insertTrip.setDouble(13, trip.getFareAmount());
        insertTrip.setDouble(14, trip.getSurcharge());
        insertTrip.setDouble(15, trip.getMtaTax());
        insertTrip.setDouble(16, trip.getTipAmount());
        insertTrip.setDouble(17, trip.getTollsAmount());
        insertTrip.setDouble(18, trip.getTotalAmount());
        insertTrip.setLong(19, trip.getTimestampReceived());

        insertTrip.execute();
    } catch (SQLException e) {
        LOGGER.log(Level.SEVERE, "Problem when inserting ticket into DB for ticket = " + trip
                + " from thread = " + Thread.currentThread());
    } finally {
        try {
            if (insertTrip != null)
                insertTrip.close();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Problem with closing prepared statement for ticket = " + trip
                    + " from thread = " + Thread.currentThread());
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Problem with closing connection from thread = " + Thread.currentThread());
        }
        //            LOGGER.log(Level.INFO, "Finished inserting ticket into DB for for ticket = " +
        //                    trip + " from thread = " + Thread.currentThread());
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.approval.JdbcApprovalStore.java

public boolean purgeExpiredApprovals() {
    logger.debug("Purging expired approvals from database");
    try {/*from  www.  ja va 2  s .  c  om*/
        int deleted = jdbcTemplate.update(DELETE_AUTHZ_SQL + " where expiresAt <= ?",
                new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps) throws SQLException {
                        ps.setTimestamp(1, new Timestamp(new Date().getTime()));
                    }
                });
        logger.debug(deleted + " expired approvals deleted");
    } catch (DataAccessException ex) {
        logger.error("Error purging expired approvals", ex);
        return false;
    }
    return true;
}

From source file:net.solarnetwork.node.dao.jdbc.general.JdbcGeneralLocationDatumDao.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void setDatumUploaded(final GeneralLocationDatum datum, Date date, String destination,
        String trackingId) {//  w  w w .  j  ava 2 s  .  c o  m
    final long timestamp = (date == null ? System.currentTimeMillis() : date.getTime());
    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(getSqlResource(SQL_RESOURCE_UPDATE_UPLOADED));
            int col = 1;
            ps.setTimestamp(col++, new java.sql.Timestamp(timestamp));
            ps.setTimestamp(col++, new java.sql.Timestamp(datum.getCreated().getTime()));
            ps.setObject(col++, datum.getLocationId());
            ps.setObject(col++, datum.getSourceId());
            return ps;
        }
    });
}

From source file:net.solarnetwork.node.dao.jdbc.power.JdbcPowerDatumDao.java

@Override
protected void setStoreStatementValues(PowerDatum datum, PreparedStatement ps) throws SQLException {
    int col = 1;//from   w  ww . j av a 2  s  .  c  om
    ps.setTimestamp(col++, new java.sql.Timestamp(
            datum.getCreated() == null ? System.currentTimeMillis() : datum.getCreated().getTime()));
    ps.setString(col++, datum.getSourceId() == null ? "" : datum.getSourceId());
    if (datum.getLocationId() == null) {
        ps.setNull(col++, Types.BIGINT);
    } else {
        ps.setLong(col++, datum.getLocationId());
    }
    if (datum.getWatts() == null) {
        ps.setNull(col++, Types.INTEGER);
    } else {
        ps.setInt(col++, datum.getWatts());
    }
    if (datum.getBatteryVolts() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getBatteryVolts());
    }
    if (datum.getBatteryAmpHours() == null) {
        ps.setNull(col++, Types.DOUBLE);
    } else {
        ps.setDouble(col++, datum.getBatteryAmpHours());
    }
    if (datum.getDcOutputVolts() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getDcOutputVolts());
    }
    if (datum.getDcOutputAmps() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getDcOutputAmps());
    }
    if (datum.getAcOutputVolts() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getAcOutputVolts());
    }
    if (datum.getAcOutputAmps() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getAcOutputAmps());
    }
    if (datum.getWattHourReading() == null) {
        ps.setNull(col++, Types.BIGINT);
    } else {
        ps.setLong(col++, datum.getWattHourReading());
    }
    if (datum.getAmpHourReading() == null) {
        ps.setNull(col++, Types.DOUBLE);
    } else {
        ps.setDouble(col++, datum.getAmpHourReading());
    }
}

From source file:com.thinkbiganalytics.ingest.GetTableDataSupport.java

/**
 * Provides an incremental select based on a date field and last status. The overlap time will be subtracted from
 * the last load date. This will cause duplicate records but also pickup records that were missed on the last scan
 * due to long-running transactions.//from   w w  w .  ja v a  2  s . c  o  m
 *
 * @param tableName    the table
 * @param dateField    the name of the field containing last modified date used to perform the incremental load
 * @param overlapTime  the number of seconds to overlap with the last load status
 * @param lastLoadDate the last batch load date
 */
public ResultSet selectIncremental(String tableName, String[] selectFields, String dateField, int overlapTime,
        Date lastLoadDate, int backoffTime, UnitSizes unit) throws SQLException {
    ResultSet rs = null;

    logger.info(
            "selectIncremental tableName {} dateField {} overlapTime {} lastLoadDate {} backoffTime {} unit {}",
            tableName, dateField, overlapTime, lastLoadDate, backoffTime, unit.toString());

    final Date now = new Date(DateTimeUtils.currentTimeMillis());
    DateRange range = new DateRange(lastLoadDate, now, overlapTime, backoffTime, unit);

    logger.info("Load range with min {} max {}", range.getMinDate(), range.getMaxDate());

    StringBuilder sb = new StringBuilder();
    String select = selectStatement(selectFields, "tbl");
    sb.append("select ").append(select).append(" from ").append(tableName).append(" tbl WHERE tbl.")
            .append(dateField).append(" > ? and tbl.").append(dateField).append(" < ?");

    if (range.getMinDate().before(range.getMaxDate())) {
        PreparedStatement ps = conn.prepareStatement(sb.toString());
        ps.setQueryTimeout(timeout);
        ps.setTimestamp(1, new java.sql.Timestamp(range.getMinDate().getTime()));
        ps.setTimestamp(2, new java.sql.Timestamp(range.getMaxDate().getTime()));

        logger.info("Executing incremental GetTableData query {}", ps);
        rs = ps.executeQuery();
    }
    return rs;
}