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:netflow.DatabaseProxy.java

public void doAggregation() {
    //todo: the same for doAggregation(Date)
    String sql = getQuery("aggregation.insert");
    String logStr = "doAggregation(): ";
    log.info(logStr + " <<<<");
    try {/*from ww w  .  ja v  a  2  s  . c  o m*/
        List<Integer> clients = getNetworkedClients();
        PreparedStatement pst = con.prepareStatement(sql);

        for (Integer client : clients) {
            Collection<AggregationRecord> records = askForData(client);
            for (AggregationRecord record : records) {
                pst.setInt(1, record.getClientId());
                pst.setTimestamp(2, record.getStamp());
                pst.setLong(3, record.getInput());
                pst.setLong(4, record.getOutput());
                pst.addBatch();
            }
        }

        pst.executeBatch();
        pst.close();
    } catch (SQLException e) {
        log.error(logStr + " Aggregation error: " + e.getMessage());
        e.printStackTrace(System.err);
    }
    log.info(logStr + " >>>>");
}

From source file:com.moss.schematrax.SchemaUpdater.java

private void recordUpdate(Connection sqlConnection, String schema, SchemaUpdate update) throws SQLException {
    PreparedStatement preparedStatement = sqlConnection
            .prepareStatement("INSERT INTO " + schema + ".SCHEMA_UPDATES values (?,?)");
    preparedStatement.setString(1, update.getId());
    preparedStatement.setTimestamp(2, new java.sql.Timestamp(new Date().getTime()));
    preparedStatement.execute();//ww  w . j  a  v  a 2  s .c  o m
    if (manageTransactions)
        sqlConnection.commit();
}

From source file:com.biomeris.i2b2.export.engine.i2b2comm.I2b2DBCommunicator.java

public int countObservationsQuery(Concept concept) throws SQLException, ExportCellException {
    String conceptCdQuery = conceptCdQuery(concept);
    String modifierCdQuery = modifierCdQuery(concept.getModifier());

    String countQuery = "SELECT count(*) c FROM " + crc_dbFullSchema
            + ".observation_fact WHERE patient_num IN (" + patientSetQuery + ") AND concept_cd IN ("
            + conceptCdQuery + ")";
    if (modifierCdQuery != null) {
        countQuery += " AND modifier_cd IN(" + modifierCdQuery + ")";
    }//  w  w w .  java 2s .  co  m

    int startDateParam = 0;
    if (export.getExportParams().getStartDate() != null) {
        countQuery += " AND start_date > ? ";
        startDateParam = 1;
    }

    int endDateParam = 0;
    if (export.getExportParams().getEndDate() != null) {
        countQuery += " AND start_date < ? ";
        endDateParam = startDateParam + 1;
    }

    PreparedStatement countStmt = null;
    ResultSet countRS = null;
    try {
        countStmt = demodataConnection.prepareStatement(countQuery);

        if (startDateParam > 0) {
            Timestamp start = new Timestamp(export.getExportParams().getStartDate().getTimeInMillis());
            countStmt.setTimestamp(startDateParam, start);
        }

        if (endDateParam > 0) {
            Timestamp end = new Timestamp(export.getExportParams().getEndDate().getTimeInMillis());
            countStmt.setTimestamp(endDateParam, end);
        }

        log.debug(countStmt);

        countRS = countStmt.executeQuery();

        if (countRS.next()) {
            int count = countRS.getInt("c");
            return count;
        } else {
            throw new ExportCellException("Something went wrong with count query");
        }
    } finally {
        if (countRS != null) {
            countRS.close();
        }
        if (countStmt != null) {
            countStmt.close();
        }
    }
}

From source file:net.mindengine.oculus.frontend.service.issue.JdbcIssueDAO.java

@Override
public long createIssue(Issue issue) throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into issues (name, link, summary, description, author_id, date, fixed, fixed_date, project_id, subproject_id) "
                    + "values (?,?,?,?,?,?,?,?,?,?)");

    ps.setString(1, issue.getName());/*  ww w.jav a2s.c  o  m*/
    ps.setString(2, issue.getLink());
    ps.setString(3, issue.getSummary());
    ps.setString(4, issue.getDescription());
    ps.setLong(5, issue.getAuthorId());
    ps.setTimestamp(6, new Timestamp(issue.getDate().getTime()));
    ps.setInt(7, issue.getFixed());
    ps.setTimestamp(8, new Timestamp(issue.getFixedDate().getTime()));
    ps.setLong(9, issue.getProjectId());
    ps.setLong(10, issue.getSubProjectId());

    logger.info(ps);

    ps.execute();

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

From source file:dk.dma.msinm.legacy.msi.service.LegacyMsiImportService.java

/**
 * Import active MSI warnings//from  w w  w.j  a  v  a 2  s.c  o m
 * @param sql the sql for fetching IDS
 * @return the last updated date
 */
public Date importMsi(List<LegacyMessage> result, String sql, String type, Date... dataParams) {
    log.debug("Start importing at most " + LIMIT + " " + type + " legacy MSI warnings from local DB");

    Date lastUpdate = null;
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = legacyDatabase.getConnection();

        stmt = conn.prepareStatement(sql);

        // Set the parameters, which must consist of a set of data parameters,
        // and lastly a limit parameter
        for (int x = 0; x < dataParams.length; x++) {
            stmt.setTimestamp(x + 1, new Timestamp(dataParams[x].getTime()));
        }
        stmt.setInt(dataParams.length + 1, LIMIT);

        log.debug("Executing SQL\n" + sql);
        long t0 = System.currentTimeMillis();

        // Fetch ID's of active MSI
        List<Integer> ids = new ArrayList<>();
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            ids.add(rs.getInt("id"));
        }
        rs.close();
        log.debug(String.format("Fetched %d ID's for %s legacy MSI in %d ms", ids.size(), type,
                System.currentTimeMillis() - t0));

        // Import the MSI's
        if (ids.size() > 0) {
            lastUpdate = importMsi(ids, conn, result);
        }

    } catch (Exception ex) {
        log.error("Failed fetching active legacy MSI messages from database ", ex);
    } finally {
        try {
            stmt.close();
        } catch (Exception ex) {
        }
        try {
            conn.close();
        } catch (Exception ex) {
        }
    }

    return lastUpdate;
}

From source file:no.polaric.aprsdb.MyDBSession.java

/**
 * Get trail for a given station and a given time span. 
 *///from  w ww .  j  a  v a  2  s.c o  m
public DbList<TPoint> getTrail(String src, java.util.Date from, java.util.Date to, boolean rev)
        throws java.sql.SQLException {
    _log.debug("MyDbSession", "getTrail: " + src + ", " + df.format(from) + " - " + df.format(to));
    PreparedStatement stmt = getCon().prepareStatement(
            " SELECT * FROM \"PosReport\"" + " WHERE src=? AND time >= ? AND time <= ?" + " ORDER BY time "
                    + (rev ? "DESC" : "ASC") + " LIMIT 500",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    stmt.setString(1, src);
    stmt.setTimestamp(2, date2ts(from));
    stmt.setTimestamp(3, date2ts(to));
    stmt.setMaxRows(500);

    return new DbList(stmt.executeQuery(), rs -> {
        return new TPoint(rs.getTimestamp("time"), getRef(rs, "position"));
    });
}

From source file:netflow.DatabaseProxy.java

public void saveHosts(Map<String, HostTraffic> cache, java.util.Date date) {
    if (cache.size() == 0) {
        log.debug("Host cache empty");
        return;/*from  w  w  w . j  av a  2  s . c  om*/
    }
    log.debug("Saving " + cache.size() + " records for " + date);
    String sql = getQuery("neflow.details.insert");
    try {
        PreparedStatement pstmt = con.prepareStatement(sql);
        Timestamp t = new java.sql.Timestamp(date.getTime());
        for (String key : cache.keySet()) {
            HostTraffic traffic = cache.get(key);
            if (!hasRecord(t, traffic.getHostAddress(), traffic.getNetworkId())) {
                pstmt.setTimestamp(1, t);
                pstmt.setString(2, traffic.getHostAddress());
                pstmt.setInt(3, traffic.getNetworkId());
                pstmt.setLong(4, traffic.getInputBytes());
                pstmt.setLong(5, traffic.getOutputBytes());
                pstmt.addBatch();
            }
        }
        int[] results = pstmt.executeBatch();
        log.info("saveHosts(): saved " + results.length + " records");
        pstmt.close();
        pstmt.clearParameters();
    } catch (SQLException e) {
        log.error("Saving hosts error: " + e.getMessage());
        SQLException ex = e.getNextException();
        if (ex != null) {
            log.error(ex.getMessage());
        }
        e.printStackTrace(System.err);
    }
}

From source file:mysql5.MySQL5PlayerDAO.java

@Override
public void storeLastOnlineTime(final int objectId, final Timestamp lastOnline) {
    DB.insertUpdate("UPDATE players set last_online = ? where id = ?", new IUStH() {
        @Override/* ww  w. j av  a2 s  .c o m*/
        public void handleInsertUpdate(PreparedStatement preparedStatement) throws SQLException {
            preparedStatement.setTimestamp(1, lastOnline);
            preparedStatement.setInt(2, objectId);
            preparedStatement.execute();
        }
    });
}

From source file:edu.northwestern.bioinformatics.studycalendar.domain.tools.hibernate.ScheduledActivityStateType.java

public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws HibernateException, SQLException {
    ScheduledActivityState toSet = (ScheduledActivityState) value;
    Timestamp date = null;// ww w  . j  a  va2s .c  o  m
    String reason = null;
    ScheduledActivityMode mode = null;
    Boolean withTime = false;
    if (toSet != null) {
        mode = toSet.getMode();
        reason = toSet.getReason();

        Date dateToSet = toSet.getDate();
        date = dateToSet == null ? null : new Timestamp(dateToSet.getTime());
        if (toSet.getWithTime()) {
            withTime = true;
        }
    }

    HibernateTypeUtils.logBind(log, index + DATE_INDEX, date);
    st.setTimestamp(index + DATE_INDEX, date);

    HibernateTypeUtils.logBind(log, index + WITH_TIME_INDEX, withTime);
    st.setBoolean(index + WITH_TIME_INDEX, withTime);

    HibernateTypeUtils.logBind(log, index + REASON_INDEX, reason);
    st.setString(index + REASON_INDEX, reason);

    MODE_TYPE.nullSafeSet(st, mode, index + MODE_INDEX, session);
}

From source file:mysql5.MySQL5PlayerDAO.java

/**
 * {@inheritDoc}/*from w  ww.jav  a  2s  .  c  o  m*/
 */
@Override
public void updateDeletionTime(final int objectId, final Timestamp deletionDate) {
    DB.insertUpdate("UPDATE players set deletion_date = ? where id = ?", new IUStH() {
        @Override
        public void handleInsertUpdate(PreparedStatement preparedStatement) throws SQLException {
            preparedStatement.setTimestamp(1, deletionDate);
            preparedStatement.setInt(2, objectId);
            preparedStatement.execute();
        }
    });
}