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:net.sf.infrared.collector.impl.persistence.ApplicationStatisticsDaoImpl.java

void saveLayerTimes(final ApplicationStatistics stats) {
    final String appName = stats.getApplicationName();
    final String instanceId = stats.getInstanceId();

    final String[] layers = stats.getLayers();

    getJdbcTemplate().batchUpdate(SQL_INSERT_LAYER_TIME, new BatchPreparedStatementSetter() {
        public int getBatchSize() {
            return layers.length;
        }//from  w ww.j a  v a  2  s. c o m

        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, appName);
            ps.setString(2, instanceId);
            ps.setString(3, layers[i]);
            ps.setLong(4, stats.getTimeInLayer(layers[i]));
            ps.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
        }
    });
    if (log.isDebugEnabled()) {
        log.debug("Saved " + layers.length + " layer times in " + stats + " to DB");
    }
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

private void insertIdeaInstance(IdeaInstance ideainstance, Connection conn) {
    PreparedStatement stat = null;
    try {//  ww w .  jav a  2 s.co m
        stat = conn.prepareStatement(ADD_IDEAINSTANCE);
        int index = 1;
        stat.setString(index++, ideainstance.getCode());
        if (null != ideainstance.getCreatedat()) {
            Timestamp createdatTimestamp = new Timestamp(ideainstance.getCreatedat().getTime());
            stat.setTimestamp(index++, createdatTimestamp);
        } else {
            stat.setNull(index++, Types.DATE);
        }
        stat.executeUpdate();
    } catch (Throwable t) {
        _logger.error("Error in insert ideainstance", t);
        throw new RuntimeException("Error in insert ideainstance", t);
    } finally {
        this.closeDaoResources(null, stat, null);
    }
}

From source file:eu.celarcloud.celar_ms.ServerPack.Database.MySQL.DBHandlerWithConnPool.java

public void insertBatchMetricValues(ArrayList<MetricObj> metriclist) {
    PreparedStatement stmt = null;
    Connection c = null;//from ww w . j  av  a2  s . c o  m
    try {
        c = this.getConnection();
        stmt = c.prepareStatement(INSERT_METRIC_VALUE);
        for (MetricObj metric : metriclist) {
            stmt.setString(1, metric.getMetricID());
            stmt.setTimestamp(2, new java.sql.Timestamp(metric.getTimestamp()));
            stmt.setString(3, metric.getValue());
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        server.writeToLog(Level.SEVERE, "MySQL Handler insertBatchMetricValues>> " + e);
    } catch (Exception e) {
        server.writeToLog(Level.SEVERE, "MySQL Handler insertBatchMetricValues>> " + e);
    } finally {
        this.release(stmt, c);
    }

}

From source file:nz.co.senanque.locking.sql.SQLLockFactory.java

public boolean lock(SQLLock oracleLock) {
    String lockName = oracleLock.getLockName();
    String ownerName = getThreadid();
    Connection connection = null;
    try {//from w w  w.  j ava 2s.c  o m
        connection = m_dataSource.getConnection();
        PreparedStatement read = null;
        ResultSet rs = null;

        try {
            read = connection.prepareStatement("select * from SQL_LOCK where lockName = ?");
            read.setString(1, lockName);
            rs = read.executeQuery();
            if (rs.next()) {
                String lockOwner = rs.getString("ownerName");
                if (lockOwner.equals(ownerName)) {
                    // We own this lock so we are okay
                    logger.debug("Lock {} already secured for us: {}", lockName, ownerName);
                    return true;
                }
                // we found a lock that we don't own.
                logger.debug("Lock {} already secured for {} rejected request from {}",
                        new Object[] { lockName, lockOwner, ownerName });
                return false;
            }
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (read != null) {
                read.close();
            }
        }

        // The item is probably not already locked (ie it might get locked between the time we checked and now)
        // So attempt to lock it by creating a record with that unique key
        PreparedStatement insert = null;
        try {
            insert = connection.prepareStatement(
                    "insert into SQL_LOCK (lockName,ownerName,started,comments,hostAddress) values (?,?,?,?,?)");
            insert.setString(1, lockName);
            insert.setString(2, ownerName);
            Date d = new Date();
            insert.setTimestamp(3, new Timestamp(d.getTime()));
            insert.setString(4, oracleLock.getComment());
            insert.setString(5, m_hostAddress);

            int count = insert.executeUpdate();
            return (count == 1);
        } catch (SQLException e1) {
            return false; // failure to insert the record means it must be locked.
            //         throw new RuntimeException(e1);
        } finally {
            if (insert != null) {
                insert.close();
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        close(connection);
    }
}

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

@Override
Stat createInode(String id, int type, int uid, int gid, int mode, int nlink, long size) {
    /* H2 uses weird names for the column with the auto-generated key, so we cannot use the code
     * in the base class.//w  w  w  . j av a2 s .co m
     */
    Timestamp now = new Timestamp(System.currentTimeMillis());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    _jdbc.update(con -> {
        PreparedStatement ps = con.prepareStatement(
                "INSERT INTO t_inodes (ipnfsid,itype,imode,inlink,iuid,igid,isize,iio,"
                        + "ictime,iatime,imtime,icrtime,igeneration) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, id);
        ps.setInt(2, type);
        ps.setInt(3, mode & UnixPermission.S_PERMS);
        ps.setInt(4, nlink);
        ps.setInt(5, uid);
        ps.setInt(6, gid);
        ps.setLong(7, size);
        ps.setInt(8, _ioMode);
        ps.setTimestamp(9, now);
        ps.setTimestamp(10, now);
        ps.setTimestamp(11, now);
        ps.setTimestamp(12, now);
        ps.setLong(13, 0);
        return ps;
    }, keyHolder);

    Stat stat = new Stat();
    stat.setIno((Long) keyHolder.getKey());
    stat.setId(id);
    stat.setCrTime(now.getTime());
    stat.setGeneration(0);
    stat.setSize(size);
    stat.setATime(now.getTime());
    stat.setCTime(now.getTime());
    stat.setMTime(now.getTime());
    stat.setUid(uid);
    stat.setGid(gid);
    stat.setMode(mode & UnixPermission.S_PERMS | type);
    stat.setNlink(nlink);
    stat.setDev(17);
    stat.setRdev(13);

    return stat;
}

From source file:com.concursive.connect.cms.portal.dao.DashboardPortlet.java

public void insert(Connection db) throws SQLException {
    // Insert the page
    PreparedStatement pst = db.prepareStatement("INSERT INTO project_dashboard_portlet "
            + "(page_id, portlet_id " + (entered != null ? ", entered " : "")
            + (modified != null ? ", modified " : "") + ") VALUES (?, ?" + (entered != null ? ", ? " : "")
            + (modified != null ? ", ? " : "") + ")");
    int i = 0;/* w  w w  . j  av a 2 s . c  om*/
    pst.setInt(++i, pageId);
    pst.setInt(++i, portletId);
    if (entered != null) {
        pst.setTimestamp(++i, entered);
    }
    if (modified != null) {
        pst.setTimestamp(++i, modified);
    }
    pst.execute();
    pst.close();
    id = DatabaseUtils.getCurrVal(db, "project_dashboard_portlet_page_portlet_id_seq", -1);
}

From source file:com.iucosoft.eavertizare.dao.impl.ClientsDaoImpl.java

@Override
public void saveLocal(Firma firma, List<Client> clientsList) {

    String query = "INSERT INTO " + firma.getTabelaClientiLocal() + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
    Connection con = null;/*from   w ww.  ja  v  a  2  s  .c  o m*/
    PreparedStatement ps = null;
    try {
        con = dataSource.getConnection();
        ps = con.prepareStatement(query);
        // Set auto-commit to false
        con.setAutoCommit(false);

        for (Client client : clientsList) {
            ps.setInt(1, client.getId());
            ps.setString(2, client.getNume());
            ps.setString(3, client.getPrenume());
            ps.setInt(4, client.getNrTelefon());
            ps.setString(5, client.getEmail());
            ps.setTimestamp(6, (new java.sql.Timestamp(client.getDateExpirare().getTime())));
            ps.setInt(7, firma.getId());
            ps.setInt(8, 0);

            ps.addBatch();
        }

        // Create an int[] to hold returned values
        int[] count = ps.executeBatch();
        //Explicitly commit statements to apply changes
        con.commit();

    } catch (SQLException e) {
        e.printStackTrace();
        try {
            con.rollback();
        } catch (SQLException ex) {
            Logger.getLogger(ClientsDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        try {
            ps.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:netflow.DatabaseProxy.java

public void doAggregation(Date date) {
    if (date == null) {
        doAggregation();/*from   w  w  w  . j  av a2s  .co  m*/
        return;
    }

    String logStr = "doAggregation(): ";
    Timestamp start = Utils.getStartDate(date);
    Timestamp end = Utils.getEndDate(date);
    try {
        //todo: optimize as per ticket #21
        String sql = getQuery("aggregation.bydate.insert");
        log.info(logStr + " <<<<");
        List<Integer> clients = getNetworkedClients();
        PreparedStatement pstmt = con.prepareStatement(sql);
        for (Integer client : clients) {
            log.debug("Client " + client);
            start = getStartTimestamp(start, end, client);
            pstmt.setTimestamp(1, start);
            pstmt.setTimestamp(2, end);
            pstmt.setInt(3, client);
            log.debug("Minutes aggregation");
            pstmt.executeUpdate();
            log.debug("Minutes aggregation done");
        }
        pstmt.close();
    } catch (SQLException e) {
        log.error(logStr + " Aggregation error: " + e.getMessage());
        e.printStackTrace(System.err);
    }
    log.info(logStr + " >>>>");
}

From source file:eu.celarcloud.jcatascopia.web.queryMaster.database.MySQL.DBInterfaceWithConnPool.java

/**
 * Connects to the given database and retrieves all the values between the given timerange
 * for the given metric//ww  w. ja v a 2 s .  c  o  m
 * UNIX TIME
 */
public ArrayList<MetricObj> getMetricValuesByTime(String metricID, long start, long end) {
    PreparedStatement stmt = null;
    Connection c = null;
    try {
        c = this.getConnection();
        stmt = c.prepareStatement(GET_METRIC_VALUES_BY_TIMERANGE);
        stmt.setString(1, metricID);
        stmt.setTimestamp(2, new Timestamp(start * 1000));
        stmt.setTimestamp(3, new Timestamp(end * 1000));

        ResultSet rs = stmt.executeQuery();
        ArrayList<MetricObj> metriclist = new ArrayList<MetricObj>();
        String t = "";
        while (rs.next()) {
            t = rs.getString("timestamp").split(" ")[1].replace(".0", "");
            metriclist.add(new MetricObj(rs.getString("metricID"), rs.getString("name"), rs.getString("units"),
                    rs.getString("type"), rs.getString("mgroup"), rs.getString("value"), t));
        }
        return metriclist;
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        this.release(stmt, c);
    }
    return null;
}

From source file:io.netty.example.file.FileServerHandler.java

private void insertRecordIntoTable(String fileName, String newFileName) throws SQLException {

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String sql = "INSERT INTO T_FILE_UPLOAD" + "(F_NO, F_FILE_NAME, F_NEW_FILE_NAME, F_DATETIME, F_YMD) VALUES"
            + "(null,?,?,?,?)";

    try {// www .  j  ava  2  s .c o  m
        dbConnection = connectionPool.getConnection();
        preparedStatement = dbConnection.prepareStatement(sql);
        preparedStatement.setString(1, fileName);
        preparedStatement.setString(2, newFileName);
        preparedStatement.setTimestamp(3, getCurrentTimeStamp());
        preparedStatement.setString(4, getToday());

        // execute insert SQL stetement
        preparedStatement.executeUpdate();

        logger.debug("Record is inserted into DBUSER table!");

    } catch (SQLException e) {

        logger.fatal(e.getMessage());

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

        if (connectionPool != null) {
            connectionPool.shutdown();
        }
    }

}