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.zuoxiaolong.dao.ArticleDao.java

public Map<String, String> getPreArticle(final int id, final Date createDate, final ViewMode viewMode) {
    return execute((Operation<Map<String, String>>) connection -> {
        String sql = "SELECT * FROM articles WHERE create_date<? AND status=1 AND "
                + "TYPE=(SELECT TYPE FROM articles WHERE id=?) ORDER BY create_date DESC LIMIT 0,1";
        Map<String, String> result = null;
        try {/*from w  w  w .  j ava  2  s  . c o  m*/
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setTimestamp(1, new Timestamp(createDate.getTime()));
            statement.setInt(2, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                result = transfer(resultSet, viewMode);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    });
}

From source file:com.zuoxiaolong.dao.ArticleDao.java

public Map<String, String> getNextArticle(final int id, final Date createDate, final ViewMode viewMode) {
    return execute((Operation<Map<String, String>>) connection -> {
        String sql = "SELECT * FROM articles WHERE create_date>? AND status=1 AND "
                + "TYPE=(SELECT TYPE FROM articles WHERE id=?) ORDER BY create_date ASC LIMIT 0,1";
        Map<String, String> result = null;
        try {/* ww w. j  av  a  2 s .c  o m*/
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setTimestamp(1, new Timestamp(createDate.getTime()));
            statement.setInt(2, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                result = transfer(resultSet, viewMode);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    });
}

From source file:com.adanac.module.blog.dao.ArticleDao.java

public Map<String, String> getPreArticle(final int id, final Date createDate, final ViewMode viewMode) {
    return execute((Operation<Map<String, String>>) connection -> {
        String sql = "SELECT * FROM articles WHERE create_date<? AND "
                + "TYPE=(SELECT TYPE FROM articles WHERE id=?) ORDER BY create_date DESC LIMIT 0,1";
        Map<String, String> result = null;
        try {//from w w  w  .java2  s  .c om
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setTimestamp(1, new Timestamp(createDate.getTime()));
            statement.setInt(2, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                result = transfer(resultSet, viewMode);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    });
}

From source file:com.adanac.module.blog.dao.ArticleDao.java

public Map<String, String> getNextArticle(final int id, final Date createDate, final ViewMode viewMode) {
    return execute((Operation<Map<String, String>>) connection -> {
        String sql = "SELECT * FROM articles WHERE create_date>? AND "
                + "TYPE=(SELECT TYPE FROM articles WHERE id=?) ORDER BY create_date ASC LIMIT 0,1";
        Map<String, String> result = null;
        try {//from  w  w  w .j a  v  a 2s.com
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setTimestamp(1, new Timestamp(createDate.getTime()));
            statement.setInt(2, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                result = transfer(resultSet, viewMode);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    });
}

From source file:com.glaf.base.test.service.MxMixFeatureTestService.java

@Transactional
public void run() {
    log.debug("-------------------start run-------------------");
    for (int i = 0; i < 2; i++) {
        SysLog bean = new SysLog();
        bean.setAccount("test");
        bean.setIp("127.0.0.1");
        bean.setOperate("add");
        sysLogService.create(bean);//  ww  w.j a  va 2  s.  com
    }

    String sql = "insert into SYS_LOG(ID, ACCOUNT, IP, CREATETIME, MODULEID, OPERATE, FLAG, TIMEMS) values (?, ?, ?, ?, ?, ?, ?, ?) ";
    Connection connection = null;
    PreparedStatement psmt = null;
    try {
        connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
        System.out.println("connection:" + connection.toString());
        psmt = connection.prepareStatement(sql);
        for (int i = 0; i < 2; i++) {
            psmt.setLong(1, idGenerator.nextId());
            psmt.setString(2, "test2");
            psmt.setString(3, "192.168.0.100");
            psmt.setTimestamp(4, DateUtils.toTimestamp(new Date()));
            psmt.setString(5, "xx");
            psmt.setString(6, "Y");
            psmt.setInt(7, 1);
            psmt.setLong(8, i * i);
            psmt.addBatch();
        }
        psmt.executeBatch();
        psmt.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
    }
    log.debug("-------------------end run-------------------");
}

From source file:net.mlw.vlh.adapter.jdbc.util.setter.Hibernate20CalendarSetter.java

/**
 * <ol>/*from w ww . j  av a  2s  .c  o m*/
 * <li>If filter value is instance of the Calendar, it will set it directly
 * to <code>PreparedStatement</code> query. </li>
 * <li>Otherwise it will set new Timestamp(with actual time) to query for
 * key.</li>
 * </ol>
 * 
 * @see net.mlw.util.sql.StatementBuilder.Setter#set(java.sql.PreparedStatement,
 *      int, java.lang.Object)
 */
public int set(PreparedStatement query, int index, Object value) throws SQLException, ParseException {
    long timeInMillis = 0;
    if (value instanceof Calendar) {
        timeInMillis = ((Calendar) value).getTimeInMillis();
    } else {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("The key's index's='" + index + "' value='" + value
                    + "' was expected as Calendar. Using actual time.");
        }
        timeInMillis = Calendar.getInstance().getTimeInMillis();
    }

    query.setTimestamp(index++, new Timestamp(timeInMillis));
    return index;
}

From source file:com.sql.Activity.java

/**
 * Inserts activity into the Activity Table after sending email message
 * //ww  w  .j  a  v a2  s  .co m
 * @param act ActivityModel
 */
public static void insertActivity(ActivityModel act) {
    Connection conn = null;
    PreparedStatement ps = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "INSERT INTO Activity (" + "caseYear, " //1
                + "caseType, " //2
                + "caseMonth, " //3
                + "caseNumber, " //4
                + "userID, " //5
                + "date, " //6
                + "action, " //7
                + "fileName, " //8
                + "[from], " //9 
                + "[to], " //10
                + "type, " //11
                + "comment, " //12
                + "redacted, " //13
                + "awaitingTimestamp "//14
                + ") VALUES (" + "?, " //1
                + "?, " //2
                + "?, " //3
                + "?, " //4
                + "?, " //5
                + "?, " //6
                + "?, " //7
                + "?, " //8
                + "?, " //9
                + "?, " //10
                + "?, " //11
                + "?, " //12
                + "?, " //13
                + "?)"; //14
        ps = conn.prepareStatement(sql);
        ps.setString(1, act.getCaseYear());
        ps.setString(2, act.getCaseType());
        ps.setString(3, act.getCaseMonth());
        ps.setString(4, act.getCaseNumber());
        ps.setString(5, act.getUserID());
        ps.setTimestamp(6, act.getDate());
        ps.setString(7, act.getAction());
        ps.setString(8, act.getFileName());
        ps.setString(9, act.getFrom());
        ps.setString(10, act.getTo());
        ps.setString(11, act.getType());
        ps.setString(12, act.getComment());
        ps.setInt(13, act.getRedacted());
        ps.setInt(14, act.getAwaitingTimestamp());
        ps.executeUpdate();
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
    }
}

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

@Override
public List<IaPrefix> findUnusedIaPrefixes(final InetAddress startAddr, final InetAddress endAddr) {
    final long offerExpiration = new Date().getTime() - 12000; // 2 min = 120 sec = 12000 ms
    List<DhcpLease> leases = getJdbcTemplate().query(
            "select * from dhcplease" + " where ((state=" + IaPrefix.ADVERTISED + " and starttime <= ?)"
                    + " or (state=" + IaPrefix.EXPIRED + " or state=" + IaPrefix.RELEASED + "))"
                    + " and ipaddress >= ? and ipaddress <= ?" + " order by state, validendtime, ipaddress",
            new PreparedStatementSetter() {
                @Override//from  w ww. j  a  va2 s .  c o  m
                public void setValues(PreparedStatement ps) throws SQLException {
                    java.sql.Timestamp ts = new java.sql.Timestamp(offerExpiration);
                    ps.setTimestamp(1, ts);
                    ps.setBytes(2, startAddr.getAddress());
                    ps.setBytes(3, endAddr.getAddress());
                }
            }, new DhcpLeaseRowMapper());
    return toIaPrefixes(leases);
}

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

@Override
public List<IaAddress> findUnusedIaAddresses(final InetAddress startAddr, final InetAddress endAddr) {
    long offerExpireMillis = DhcpServerPolicies.globalPolicyAsLong(Property.BINDING_MANAGER_OFFER_EXPIRATION);
    final long offerExpiration = new Date().getTime() - offerExpireMillis;
    List<DhcpLease> leases = getJdbcTemplate().query(
            "select * from dhcplease" + " where ((state=" + IaAddress.ADVERTISED + " and starttime <= ?)"
                    + " or (state=" + IaAddress.EXPIRED + " or state=" + IaAddress.RELEASED + "))"
                    + " and ipaddress >= ? and ipaddress <= ?" + " order by state, validendtime, ipaddress",
            new PreparedStatementSetter() {
                @Override/*from ww  w .  j a  v a2  s  . co  m*/
                public void setValues(PreparedStatement ps) throws SQLException {
                    java.sql.Timestamp ts = new java.sql.Timestamp(offerExpiration);
                    ps.setTimestamp(1, ts);
                    ps.setBytes(2, startAddr.getAddress());
                    ps.setBytes(3, endAddr.getAddress());
                }
            }, new DhcpLeaseRowMapper());
    return toIaAddresses(leases);
}

From source file:nl.nn.adapterframework.util.Locker.java

public String lock() throws JdbcException, SQLException, InterruptedException {
    Connection conn = getConnection();
    try {/*from  w w w.j  a  v  a2  s  .c  o m*/
        if (!JdbcUtil.tableExists(conn, "ibisLock")) {
            if (isIgnoreTableNotExist()) {
                log.info("table [ibisLock] does not exist, ignoring lock");
                return LOCK_IGNORED;
            } else {
                throw new JdbcException("table [ibisLock] does not exist");
            }
        }
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            log.error("error closing JdbcConnection", e);
        }
    }

    String objectIdWithSuffix = null;
    int r = -1;
    while (objectIdWithSuffix == null && (numRetries == -1 || r < numRetries)) {
        r++;
        if (r == 0 && firstDelay > 0) {
            Thread.sleep(firstDelay);
        }
        if (r > 0) {
            Thread.sleep(retryDelay);
        }
        Date date = new Date();
        objectIdWithSuffix = getObjectId();
        if (StringUtils.isNotEmpty(getDateFormatSuffix())) {
            String formattedDate = formatter.format(date);
            objectIdWithSuffix = objectIdWithSuffix.concat(formattedDate);
        }
        log.debug("preparing to set lock [" + objectIdWithSuffix + "]");
        conn = getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement(insertQuery);
            stmt.clearParameters();
            stmt.setString(1, objectIdWithSuffix);
            stmt.setString(2, getType());
            stmt.setString(3, Misc.getHostname());
            stmt.setTimestamp(4, new Timestamp(date.getTime()));
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (getType().equalsIgnoreCase("T")) {
                cal.add(Calendar.HOUR_OF_DAY, getRetention());
            } else {
                cal.add(Calendar.DAY_OF_MONTH, getRetention());
            }
            stmt.setTimestamp(5, new Timestamp(cal.getTime().getTime()));
            stmt.executeUpdate();
            log.debug("lock [" + objectIdWithSuffix + "] set");
        } catch (SQLException e) {
            log.debug(getLogPrefix() + "error executing insert query (as part of locker): " + e.getMessage());
            if (numRetries == -1 || r < numRetries) {
                log.debug(getLogPrefix() + "will try again");
                objectIdWithSuffix = null;
            } else {
                log.debug(getLogPrefix() + "will not try again");
                throw e;
            }
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("error closing JdbcConnection", e);
            }
        }
    }
    return objectIdWithSuffix;
}