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:at.alladin.rmbt.statisticServer.OpenTestSearchResource.java

/**
 * Fills in the given fields in the queue into the given prepared statement
 * @param ps/*from w w  w.  j  a  v  a2  s.  c  om*/
 * @param searchValues
 * @param firstField
 * @return
 * @throws SQLException
 */
private static PreparedStatement fillInWhereClause(PreparedStatement ps,
        Queue<Map.Entry<String, FieldType>> searchValues, int firstField) throws SQLException {
    //insert all values in the prepared statement in the order
    //in which the values had been put in the queue
    for (Map.Entry<String, FieldType> entry : searchValues) {
        switch (entry.getValue()) {
        case STRING:
            ps.setString(firstField, entry.getKey());
            break;
        case DATE:
            ps.setTimestamp(firstField, new Timestamp(Long.parseLong(entry.getKey())));
            break;
        case LONG:
            ps.setLong(firstField, Long.parseLong(entry.getKey()));
            break;
        case DOUBLE:
            ps.setDouble(firstField, Double.parseDouble(entry.getKey()));
            break;
        case UUID:
            ps.setObject(firstField, UUID.fromString(entry.getKey()));
            break;
        case BOOLEAN:
            ps.setBoolean(firstField, Boolean.valueOf(entry.getKey()));
            break;
        }
        firstField++;
    }
    return ps;
}

From source file:com.starit.diamond.server.service.DBPersistService.java

public void updateConfigInfo(final Timestamp time, final ConfigInfo configInfo) {

    this.jt.update(
            "update config_info set content=?,md5=?,gmt_modified=?,description=? where data_id=? and group_id=?",
            new PreparedStatementSetter() {

                public void setValues(PreparedStatement ps) throws SQLException {
                    int index = 1;
                    ps.setString(index++, configInfo.getContent());
                    ps.setString(index++, configInfo.getMd5());
                    ps.setTimestamp(index++, time);
                    ps.setString(index++, configInfo.getDescription());
                    ps.setString(index++, configInfo.getDataId());
                    ps.setString(index++, configInfo.getGroup());
                }/*from   ww  w. j av  a 2 s  . c o  m*/
            });
}

From source file:edu.umass.cs.gnsclient.client.util.keystorage.SimpleKeyStore.java

private void updateReadTime(String key) throws SQLException {
    if (!suppressUpdateRead) {
        PreparedStatement updateStatement = conn
                .prepareStatement("UPDATE " + TABLE_NAME + " SET READTIME=? WHERE KEYFIELD=?");
        updateStatement.setTimestamp(1, new Timestamp(new Date().getTime()));
        updateStatement.setString(2, key);
        updateStatement.executeUpdate();
    }/* ww w .  jav  a 2s  .  c o  m*/
}

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

public List<IaAddress> findUnusedByRange(final InetAddress startAddr, final InetAddress endAddr) {
    final long offerExpiration = new Date().getTime() - 12000; // 2 min = 120 sec = 12000 ms
    return getJdbcTemplate().query(
            "select * from iaaddress" + " 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  w  w w  .  j  av a2s .c om
                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 IaAddrRowMapper());
}

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

public List<IaPrefix> findUnusedByRange(final InetAddress startAddr, final InetAddress endAddr) {
    final long offerExpiration = new Date().getTime() - 12000; // 2 min = 120 sec = 12000 ms
    return getJdbcTemplate().query("select * from iaprefix" + " where ((state=" + IaPrefix.ADVERTISED
            + " and starttime <= ?)" + " or (state=" + IaPrefix.EXPIRED + " or state=" + IaPrefix.RELEASED
            + "))" + " and prefixaddress >= ? and prefixaddress <= ?"
            + " order by state, validendtime, ipaddress", new PreparedStatementSetter() {
                @Override//from   ww  w.  j ava  2 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 IaPrefixRowMapper());
}

From source file:br.inpe.XSDMiner.MineXSD.java

@Override
public void process(SCMRepository repo, Commit commit, PersistenceMechanism writer) {

    String projectName = "";
    String fullName = "";

    try {/*ww w . j a  v  a 2 s . c om*/
        if (!commit.getBranches().contains("master"))
            return;

        if (commit.isMerge())
            return;

        Class.forName("org.postgresql.Driver");
        projectName = repo.getPath().substring(repo.getPath().lastIndexOf("/") + 1);

        for (Modification m : commit.getModifications()) {
            String fName = m.getFileName();
            String addrem = "";
            String fullNameNew = m.getNewPath();
            String fullNameOld = m.getOldPath();
            if (fullNameNew.equals("/dev/null")) {
                addrem = "r";
                fullName = fullNameOld;
            } else {
                fullName = fullNameNew;
            }

            if (fullNameOld.equals("/dev/null")) {
                addrem = "a";
            }

            String fileExtension = fName.substring(fName.lastIndexOf(".") + 1);

            boolean isWSDL = fileExtension.equals("wsdl");
            boolean isXSD = fileExtension.equals("xsd");

            if (!(isWSDL || isXSD))
                continue;

            InputStream input = new ByteArrayInputStream(m.getSourceCode().getBytes(StandardCharsets.UTF_8));
            ByteArrayOutputStream outputXSD = new ByteArrayOutputStream();

            String[] schemas;
            if (fileExtension.equals("wsdl")) {
                XSDExtractor.wsdlToXSD(input, outputXSD);
                schemas = XSDExtractor.splitXSD(outputXSD.toString());

            } else {
                outputXSD.write(IOUtils.toString(input).getBytes());
                schemas = new String[1];
                schemas[0] = outputXSD.toString();
            }

            String url = "jdbc:postgresql://localhost/xsdminer";
            Properties props = new Properties();
            props.setProperty("user", "postgres");
            props.setProperty("password", "070910");
            Connection conn = DriverManager.getConnection(url, props);

            int schemaCount = schemas.length;

            for (int i = 0; i < schemaCount; i++) {
                String query = "INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                PreparedStatement st = conn.prepareStatement(query);
                st.setInt(1, i + 1);
                st.setString(2, fullName);
                st.setString(3, projectName);
                st.setString(4, commit.getHash());
                st.setTimestamp(5, new java.sql.Timestamp(commit.getDate().getTimeInMillis()));
                st.setString(6, schemas[i]);
                st.setString(7, addrem);
                st.setBoolean(8, false);
                st.executeUpdate();
                st.close();
            }
            conn.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(MineXSD.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        System.out.println("Failure - Project " + projectName + "; file: " + fullName);
        //e.printStackTrace();
    } finally {
        repo.getScm().reset();
    }
}

From source file:iddb.runtime.db.model.dao.impl.mysql.UserDAOImpl.java

@Override
public Integer cleanUp(Integer hoursLimit) {
    String sql = "delete from user_pass_rec where created < ?";
    Connection conn = null;/*  w  w w  .  j  a v a2 s .  co m*/
    Integer res = 0;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        Date limit = DateUtils.addHours(new Date(), Math.abs(hoursLimit) * -1);
        st.setTimestamp(1, new Timestamp(limit.getTime()));
        res = st.executeUpdate();
    } catch (SQLException e) {
        logger.error("cleanUp: {}", e);
    } catch (IOException e) {
        logger.error("cleanUp: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return res;
}

From source file:iddb.runtime.db.model.dao.impl.mysql.UserDAOImpl.java

@Override
public String findPassKey(String passkey, Integer hoursLimit) {
    String sql = "select * from user_pass_rec where created between ? and ? and passkey = ? limit 1";
    Connection conn = null;//from  w ww.j  a v  a  2 s  .  c  o  m
    String value = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        Date limit = DateUtils.addHours(new Date(), Math.abs(hoursLimit) * -1);
        st.setTimestamp(1, new Timestamp(limit.getTime()));
        st.setTimestamp(2, new Timestamp(new Date().getTime()));
        st.setString(3, passkey);
        ResultSet rs = st.executeQuery();
        if (rs.next()) {
            value = rs.getString("loginid");
        }
    } catch (SQLException e) {
        logger.error("findPassKey: {}", e);
    } catch (IOException e) {
        logger.error("findPassKey: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return value;
}

From source file:org.dcache.chimera.H2FsSqlDriver.java

@Override
long createTagInode(int uid, int gid, int mode, byte[] value) {
    final String CREATE_TAG_INODE_WITH_VALUE = "INSERT INTO t_tags_inodes (imode, inlink, iuid, igid, isize, "
            + "ictime, iatime, imtime, ivalue) VALUES (?,1,?,?,?,?,?,?,?)";

    Timestamp now = new Timestamp(System.currentTimeMillis());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int rc = _jdbc.update(con -> {
        PreparedStatement ps = con.prepareStatement(CREATE_TAG_INODE_WITH_VALUE,
                Statement.RETURN_GENERATED_KEYS);
        ps.setInt(1, mode | UnixPermission.S_IFREG);
        ps.setInt(2, uid);//from   w  w  w. j  a v a  2s  .  c  o  m
        ps.setInt(3, gid);
        ps.setLong(4, value.length);
        ps.setTimestamp(5, now);
        ps.setTimestamp(6, now);
        ps.setTimestamp(7, now);
        ps.setBinaryStream(8, new ByteArrayInputStream(value), value.length);
        return ps;
    }, keyHolder);
    if (rc != 1) {
        throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(CREATE_TAG_INODE_WITH_VALUE, 1, rc);
    }
    /* H2 uses weird names for the column with the auto-generated key, so we cannot use the code
     * in the base class.
     */
    return (Long) keyHolder.getKey();
}

From source file:com.hs.mail.imap.dao.MySqlMessageDao.java

private long addPhysicalMessage(final MailMessage message) {
    final String sql = "INSERT INTO physmessage (size, internaldate, subject, sentdate, fromaddr) VALUES(?, ?, ?, ?, ?)";
    final MessageHeader header = message.getHeader();
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setLong(1, message.getSize()); // size
            pstmt.setTimestamp(2, new Timestamp(message.getInternalDate().getTime())); // internaldate
            pstmt.setString(3, header.getSubject()); // subject
            Date sent = header.getDate();
            pstmt.setTimestamp(4, (sent != null) ? new Timestamp(sent.getTime()) : null); // sentdate
            pstmt.setString(5, (header.getFrom() != null) ? header.getFrom().getDisplayString() : null); // fromaddr
            return pstmt;
        }/*from  w w  w.  j  a va  2  s  .  c o m*/
    }, keyHolder);
    long physmessageid = keyHolder.getKey().longValue();
    message.setPhysMessageID(physmessageid);
    addHeader(physmessageid, header);
    return physmessageid;
}