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:eu.celarcloud.celar_ms.ServerPack.Database.MySQL.DBHandlerWithConnPool.java

public void insertMetricValue(MetricObj metric) {
    PreparedStatement stmt = null;
    Connection c = null;// w  w w  .  j av  a 2s.co  m
    try {
        c = this.getConnection();
        stmt = c.prepareStatement(INSERT_METRIC_VALUE);
        stmt.setString(1, metric.getMetricID());
        stmt.setTimestamp(2, new java.sql.Timestamp(metric.getTimestamp()));
        stmt.setString(3, metric.getValue());

        stmt.setString(4, metric.getName());
        stmt.setString(5, metric.getGroup());
        stmt.setString(6, metric.getUnits());
        stmt.setString(7, metric.getType());

        stmt.executeUpdate();
    } catch (SQLException e) {
        server.writeToLog(Level.SEVERE, "MySQL Handler insertMetricValue>> " + e);
    } catch (Exception e) {
        server.writeToLog(Level.SEVERE, "MySQL Handler insertMetricValue>> " + e);
    } finally {
        this.release(stmt, c);
    }
}

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

@Override
public List<FC_Post> getLatestPosts(final int length, final Timestamp offset, final int limit) {

    return getJdbcTemplate().query(new PreparedStatementCreator() {

        @Override/*w  w  w  . ja v  a  2  s.c  o  m*/
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(selectFromPost(length,
                    "where is_valid = true and status > 1 " + " and time_posted < ?", NUM_READ_DESC, limit));
            ps.setTimestamp(1, offset);
            return ps;
        }
    }, mapper);
}

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

@Override
public List<FC_Post> getPopularPosts(final int length, final Timestamp offset, final int limit) {

    return getJdbcTemplate().query(new PreparedStatementCreator() {

        @Override/*from   w w w  .  j a  v a 2s  .c o m*/
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(selectFromPost(length,
                    "where is_valid = true and status > 1 " + " and time_posted < ?", NUM_READ_DESC, limit));
            ps.setTimestamp(1, offset);
            return ps;
        }
    }, mapper);
}

From source file:com.surfs.storage.common.datasource.jdbc.JdbcDao.java

@Override
public int update(String poolName, String sql, Object... params) throws Exception {
    Connection conn = null;//w w  w. j a va 2 s. c o  m
    PreparedStatement ps = null;
    try {
        conn = getConnection(poolName);
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            if (params[i] instanceof String)
                ps.setString(i + 1, (String) params[i]);
            else if (params[i] instanceof Integer)
                ps.setInt(i + 1, (Integer) params[i]);
            else if (params[i] instanceof Long)
                ps.setLong(i + 1, (Long) params[i]);
            else if (params[i] instanceof Timestamp)
                ps.setTimestamp(i + 1, (Timestamp) params[i]);
        }
        return ps.executeUpdate();
    } catch (Exception e) {
        throw e;
    } finally {
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnect(conn);
    }
}

From source file:com.surfs.storage.common.datasource.jdbc.JdbcDao.java

@Override
public int delete(String poolName, String sql, Object... params) throws Exception {
    Connection conn = null;//ww  w .  j a va2  s.c  o  m
    PreparedStatement ps = null;
    try {
        conn = getConnection(poolName);
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            if (params[i] instanceof String)
                ps.setString(i + 1, (String) params[i]);
            else if (params[i] instanceof Integer)
                ps.setInt(i + 1, (Integer) params[i]);
            else if (params[i] instanceof Long)
                ps.setLong(i + 1, (Long) params[i]);
            else if (params[i] instanceof Timestamp)
                ps.setTimestamp(i + 1, (Timestamp) params[i]);
        }
        return ps.executeUpdate();
    } catch (Exception e) {
        throw e;
    } finally {
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnect(conn);
    }
}

From source file:net.bhira.sample.api.dao.DepartmentDaoImpl.java

/**
 * @see net.bhira.sample.api.dao.DepartmentDao#save(net.bhira.sample.model.Department)
 *///from w  w  w.  j a va 2  s .  c  o  m
@Override
public void save(Department department) throws ObjectNotFoundException, DuplicateNameException,
        InvalidObjectException, InvalidReferenceException {
    try {
        if (department == null) {
            throw new InvalidObjectException("Department object is null.");
        }

        department.initForSave();
        department.validate();
        boolean isNew = department.isNew();
        int count = 0;

        if (isNew) {
            // for new department, construct SQL insert statement
            KeyHolder keyHolder = new GeneratedKeyHolder();
            count = jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT,
                            Statement.RETURN_GENERATED_KEYS);
                    pstmt.setLong(1, department.getCompanyId());
                    pstmt.setString(2, department.getName());
                    pstmt.setString(3, department.getBillingAddress());
                    pstmt.setString(4, department.getShippingAddress());
                    pstmt.setTimestamp(5, new Timestamp(department.getCreated().getTime()));
                    pstmt.setTimestamp(6, new Timestamp(department.getModified().getTime()));
                    pstmt.setString(7, department.getCreatedBy());
                    pstmt.setString(8, department.getModifiedBy());
                    return pstmt;
                }
            }, keyHolder);

            // fetch the newly created auto-increment ID
            department.setId(keyHolder.getKey().longValue());
            LOG.debug("inserted department, count = {}, id = {}", count, department.getId());

        } else {
            // for existing department, construct SQL update statement
            Object[] args = new Object[] { department.getCompanyId(), department.getName(),
                    department.getBillingAddress(), department.getShippingAddress(), department.getModified(),
                    department.getModifiedBy(), department.getId() };
            count = jdbcTemplate.update(SQL_UPDATE, args);
            LOG.debug("updated department, count = {}, id = {}", count, department.getId());
        }

        // if insert/update has 0 count value, then rollback
        if (count <= 0) {
            throw new ObjectNotFoundException("Department with ID " + department.getId() + " was not found.");
        }

        // update dependent entries, as needed
        if (isNew) {

            // for new model if there is contact info, save it to contact info table and then
            // add entry in relationship table
            if (department.getContactInfo() != null) {
                contactInfoDao.save(department.getContactInfo());
                Object[] args = new Object[] { department.getId(), department.getContactInfo().getId() };
                jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
            }

        } else {
            // for existing model, fetch contact info ID from relationship table
            List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class,
                    new Object[] { department.getId() });
            Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

            if (department.getContactInfo() == null) {
                // clean up old contact info entry, if needed
                if (cinfoId != null) {
                    jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { department.getId() });
                    contactInfoDao.delete(cinfoId);
                }

            } else {
                // insert/update contact info entry
                if (cinfoId != null) {
                    department.getContactInfo().setId(cinfoId);
                    contactInfoDao.save(department.getContactInfo());
                } else {
                    contactInfoDao.save(department.getContactInfo());
                    Object[] args = new Object[] { department.getId(), department.getContactInfo().getId() };
                    jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
                }
            }
        }

    } catch (DataIntegrityViolationException dive) {
        String msg = dive.getMessage();
        if (msg != null) {
            if (msg.contains("uq_department")) {
                throw new DuplicateNameException("Duplicate department name " + department.getName(), dive);
            } else if (msg.contains("fk_department_compy")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive);
            }
        }
        throw dive;
    }
}

From source file:netflow.DatabaseProxy.java

private List<AggregationRecord> getAggregationResults(Date date) throws SQLException {
    if (date == null) {
        return getAggregationResults();
    }/*from  ww w . j  ava 2s  .  co  m*/
    log.debug("getAggregationResults(date): <<<");
    log.debug("Getting user list");

    Timestamp start = Utils.getStartDate(date);
    Timestamp end = Utils.getEndDate(date);
    log.debug("Parameters: " + start + ", " + end);

    List<Integer> clients = getNetworkedClients();
    String collect = getQuery("aggregations.forday.get");
    PreparedStatement ps = con.prepareStatement(collect);

    final List<AggregationRecord> results = new ArrayList<AggregationRecord>();
    for (Integer id : clients) {
        ps.setTimestamp(1, start);
        ps.setTimestamp(2, end);
        ps.setInt(3, id);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            results.add(new AggregationRecord(rs.getInt(1), rs.getDate(2), rs.getLong(3), rs.getLong(4)));
        }
        rs.close();
    }
    ps.close();
    log.debug("getAggregationResults(): >>>");
    return results;
}

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

@Override
public List<FC_Post> getDraftsOfAuthor(final int userId, final int length, final Timestamp offset,
        final int limit) {

    return getJdbcTemplate().query(new PreparedStatementCreator() {

        @Override/*  w w  w . ja va 2s .c  o  m*/
        public PreparedStatement createPreparedStatement(Connection arg0) throws SQLException {
            PreparedStatement ps = arg0.prepareStatement(
                    select(length) + " where id_author = ? and time_posted < ? " + TIME_DESCEND + " limit ?");
            ps.setInt(1, userId);
            ps.setTimestamp(1, offset);
            ps.setInt(3, limit);
            return ps;
        }
    }, mapper);
}

From source file:net.mindengine.oculus.frontend.service.runs.JdbcTestRunDAO.java

@Override
public Long createSuiteRun(SuiteRun suite) throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into suite_runs (start_time, end_time, name, runner_id, parameters, agent_name) "
                    + "values (?,?,?,?,?,?)");

    ps.setTimestamp(1, new Timestamp(suite.getStartTime().getTime()));
    ps.setTimestamp(2, new Timestamp(suite.getEndTime().getTime()));
    ps.setString(3, suite.getName());//from   www .ja  v  a  2s . c om
    if (suite.getRunnerId() == null)
        suite.setRunnerId(0L);
    ps.setLong(4, suite.getRunnerId());
    ps.setString(5, suite.getParameters());
    String agentName = suite.getAgentName();
    if (agentName == null) {
        agentName = "";
    }
    ps.setString(6, agentName);

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

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

From source file:net.mindengine.oculus.frontend.service.runs.JdbcTestRunDAO.java

@Override
public Long saveRun(SavedRun savedRun) throws Exception {

    PreparedStatement ps = getConnection()
            .prepareStatement("insert into saved_runs (name, user_id, date) values (?, ?, ?)");

    ps.setString(1, savedRun.getName());
    ps.setLong(2, savedRun.getUserId());
    ps.setTimestamp(3, new Timestamp(savedRun.getDate().getTime()));

    logger.info(ps);//from   ww  w  .  ja va2 s.  co  m
    ps.executeUpdate();

    ResultSet rs = ps.getGeneratedKeys();

    if (rs.next()) {
        return rs.getLong(1);

    }
    return null;
}