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:mysql5.MySQL5PlayerDAO.java

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

From source file:edu.ku.brc.specify.conversion.ConvertMiscData.java

/**
 * @param oldDBConn/*  w  w  w  . j av  a2  s  .c o  m*/
 * @param newDBConn
 * @param disciplineID
 * @return
 */
public static boolean convertKUFishCruiseData(final Connection oldDBConn, final Connection newDBConn,
        final int disciplineID) {
    PreparedStatement pStmt1 = null;
    try {
        pStmt1 = newDBConn.prepareStatement(
                "INSERT INTO collectingtrip (CollectingTripName, StartDateVerbatim, EndDateVerbatim, DisciplineID, TimestampCreated, TimestampModified, Version) VALUES(?,?,?,?,?,?,?)");

        String sql = "SELECT Text1, Text2, Number1, TimestampCreated, TimestampModified FROM stratigraphy";
        Vector<Object[]> rows = BasicSQLUtils.query(oldDBConn, sql);
        for (Object[] row : rows) {
            String vessel = (String) row[0];
            String cruiseName = (String) row[1];
            String number = row[2] != null ? Integer.toString(((Double) row[2]).intValue()) : null;

            pStmt1.setString(1, vessel);
            pStmt1.setString(2, cruiseName);
            pStmt1.setString(3, number);
            pStmt1.setInt(4, disciplineID);
            pStmt1.setTimestamp(5, (Timestamp) row[3]);
            pStmt1.setTimestamp(6, (Timestamp) row[4]);
            pStmt1.setInt(7, 0);

            pStmt1.execute();
        }
        return true;

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (pStmt1 != null)
                pStmt1.close();

        } catch (Exception ex) {
        }
    }

    return false;
}

From source file:com.krminc.phr.security.PHRRealm.java

private void doSuccessfulUpdate(String username) {
    String query = "UPDATE user_users SET failed_password_attempts = ? , failed_password_window_start = ? WHERE username = ?";
    PreparedStatement st = null;

    try {/*ww  w.j  av  a 2  s  .  c o m*/
        createDS();
        //TX for UPDATE
        conn = ds.getConnection();
        st = conn.prepareStatement(query);
        st.setInt(1, 0); //reset failed attempt count
        st.setTimestamp(2, null); //reset failed password timestamp
        st.setString(3, username);
        st.executeUpdate();
    } catch (Exception e) {
        log("Error resetting failed password values");
        log(e.getMessage());
    } finally {
        try {
            st.close();
            conn.close();
        } catch (Exception e) {
            log(e.getMessage());
        }
        conn = null;
    }
}

From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java

private void insertLastModified(String oid, long lastModified) throws Exception {
    PreparedStatement sql = connection().prepareStatement("INSERT INTO " + BASIC_TABLE
            + " (oid, cacheId, lastModified, changeFlag)" + " VALUES (?, ?, ?, 1)");

    // Prepare and execute
    sql.setString(1, oid);/* w w  w . ja  va 2s .co  m*/
    sql.setString(2, cacheId);
    sql.setTimestamp(3, new Timestamp(lastModified));
    sql.executeUpdate();
    close(sql);
}

From source file:net.mindengine.oculus.frontend.service.test.JdbcTestDAO.java

@Override
public long create(Test test) throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into tests (name, description, project_id, author_id, date, mapping, group_id, content, automated) values (?, ?, ?, ?, ?, ?, ?, ?, ?)");

    ps.setString(1, test.getName());/*from   w w w  . ja v  a2  s  . c o  m*/
    ps.setString(2, test.getDescription());
    ps.setLong(3, test.getProjectId());
    ps.setLong(4, test.getAuthorId());
    ps.setTimestamp(5, new Timestamp(test.getDate().getTime()));
    ps.setString(6, test.getMapping());
    ps.setLong(7, test.getGroupId());
    ps.setString(8, test.getContent());
    ps.setBoolean(9, test.getAutomated());

    logger.info(ps);
    ps.executeUpdate();

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

    /*
     * Increasing the tests_count value for current project
     */
    update("update projects set tests_count=tests_count+1 where id = :id", "id", test.getProjectId());
    return testId;
}

From source file:com.novartis.opensource.yada.adaptor.OracleAdaptor.java

/**
* Enables checking for {@link JDBCAdaptor#ORACLE_TIMESTAMP_FMT} if {@code val} does not conform to {@link JDBCAdaptor#STANDARD_TIMESTAMP_FMT}
* @since 5.1.1/*from ww w  . j  av  a2 s  . c om*/
*/
@Override
protected void setTimestampParameter(PreparedStatement pstmt, int index, char type, String val)
        throws SQLException {
    if (EMPTY.equals(val) || val == null) {
        pstmt.setNull(index, java.sql.Types.DATE);
    } else {
        SimpleDateFormat sdf = new SimpleDateFormat(STANDARD_TIMESTAMP_FMT);
        ParsePosition pp = new ParsePosition(0);
        Date dateVal = sdf.parse(val, pp);
        if (dateVal == null) {
            sdf = new SimpleDateFormat(ORACLE_TIMESTAMP_FMT);
            pp = new ParsePosition(0);
            dateVal = sdf.parse(val, pp);
        }
        if (dateVal != null) {
            long t = dateVal.getTime();
            java.sql.Timestamp sqlDateVal = new java.sql.Timestamp(t);
            pstmt.setTimestamp(index, sqlDateVal);
        }
    }
}

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

public Integer saveOrUpdate(String id, String subject, Status status, Type type, Integer updateCreateTime,
        String username, String html, String content, String icon) {
    return execute((TransactionalOperation<Integer>) connection -> {
        String insertSql = "insert into articles (subject,username,icon,create_date,"
                + "html,content,status,type) values (?,?,?,?,?,?,?,?)";
        String updateSql = "update articles set subject=?,username=?,icon=?,html=?,content=?,status=?,type=? where id=?";
        if (updateCreateTime == 1) {
            updateSql = "update articles set subject=?,username=?,icon=?,html=?,content=?,status=?,type=?,create_date=? where id=?";
        }/*from   www. java  2s.  c o m*/
        try {
            PreparedStatement statement = null;
            if (StringUtils.isBlank(id)) {
                statement = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
                statement.setString(1, subject);
                statement.setString(2, username);
                statement.setString(3, icon == null ? ImageUtil.randomArticleImage(subject, type) : icon);
                statement.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
                statement.setString(5, html);
                statement.setString(6, content);
                statement.setInt(7, status.getIntValue());
                statement.setInt(8, type.getIntValue());
            } else {
                statement = connection.prepareStatement(updateSql);
                statement.setString(1, subject);
                statement.setString(2, username);
                statement.setString(3, icon == null ? ImageUtil.randomArticleImage(subject, type) : icon);
                statement.setString(4, html);
                statement.setString(5, content);
                statement.setInt(6, status.getIntValue());
                statement.setInt(7, type.getIntValue());
                if (updateCreateTime == 1) {
                    statement.setTimestamp(8, new Timestamp(System.currentTimeMillis()));
                    statement.setInt(9, Integer.valueOf(id));
                } else {
                    statement.setInt(8, Integer.valueOf(id));
                }
            }
            int result = statement.executeUpdate();
            if (result > 0 && StringUtils.isBlank(id)) {
                ResultSet keyResultSet = statement.getGeneratedKeys();
                if (keyResultSet.next()) {
                    return keyResultSet.getInt(1);
                }
            }
            if (result > 0) {
                return Integer.valueOf(id);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    });
}

From source file:at.alladin.rmbt.statisticServer.UsageJSONResource.java

/**
 * Returns the statistics for used platforms for a specific timespan [begin, end)
 * @param begin select all tests with time >= begin
 * @param end select all tests with time < end
 * @return the structurized JSON object/*  w  w w  . j a v  a  2 s.c om*/
 * @throws SQLException
 * @throws JSONException
 */
private JSONObject getPlatforms(Timestamp begin, Timestamp end) throws SQLException, JSONException {
    JSONObject returnObj = new JSONObject();
    JSONArray sums = new JSONArray();
    JSONArray values = new JSONArray();
    returnObj.put("sums", sums);
    returnObj.put("values", values);

    HashMap<String, Long> fieldSums = new HashMap<>();

    PreparedStatement ps;
    ResultSet rs;

    final String sql = "SELECT date_trunc('day', time) _day, COALESCE(plattform,'null') platform, count(plattform) count_platform"
            + " FROM test" + " WHERE status='FINISHED' AND deleted=false AND time >= ? AND time < ? "
            + " GROUP BY _day, plattform" + " HAVING count(plattform) > 0" + "ORDER BY _day ASC";

    ps = conn.prepareStatement(sql);
    ps.setTimestamp(1, begin);
    ps.setTimestamp(2, end);
    rs = ps.executeQuery();

    //one array-item for each day
    long currentTime = -1;
    JSONObject currentEntry = null;
    JSONArray currentEntryValues = null;
    while (rs.next()) {

        //new item, of a new day is reached
        long newTime = rs.getDate("_day").getTime();
        if (currentTime != newTime) {
            currentTime = newTime;
            currentEntry = new JSONObject();
            currentEntryValues = new JSONArray();
            currentEntry.put("day", rs.getDate("_day").getTime());
            currentEntry.put("values", currentEntryValues);
            values.put(currentEntry);
        }

        //disable null-values
        String platform = rs.getString("platform");
        long count = rs.getLong("count_platform");
        if (platform.isEmpty()) {
            platform = "empty";
        }

        //add value to sum
        if (!fieldSums.containsKey(platform)) {
            fieldSums.put(platform, new Long(0));
        }
        fieldSums.put(platform, fieldSums.get(platform) + count);

        JSONObject current = new JSONObject();
        current.put("field", platform);
        current.put("value", count);
        currentEntryValues.put(current);
    }

    rs.close();
    ps.close();

    //add field sums
    for (String field : fieldSums.keySet()) {
        JSONObject obj = new JSONObject();
        obj.put("field", field);
        obj.put("sum", fieldSums.get(field));
        sums.put(obj);
    }

    return returnObj;
}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

public List<Transaction> getTransactionsForUser(int user_id, Date date, int page, int pageSize)
        throws SQLException {
    Connection connection = getConnection();
    List<Transaction> result = new ArrayList<Transaction>();
    PreparedStatement statement = null;
    try {/*from   www  .  ja  va 2  s. co m*/
        statement = connection.prepareStatement(GET_ALL_TRANSACTIONS_FOR_USER_STATEMENT);
        statement.setTimestamp(1, new Timestamp(date.getTime()));
        statement.setInt(2, user_id);
        statement.setInt(3, user_id);
        if (page <= 0)
            page = 1;
        statement.setInt(4, (page - 1) * (pageSize - 1)); // the offset
        statement.setInt(5, pageSize); // how many records
        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            Transaction transaction = new Transaction();
            transaction.setId(rs.getLong(1));
            transaction.setDate(rs.getTimestamp(2));
            transaction.setSource_user_id(rs.getInt(3));
            transaction.setDestination_user_id(rs.getInt(4));
            transaction.setAmount(rs.getLong(5));
            transaction.setSourceUserName(rs.getString(6));
            transaction.setDestinationUserName(rs.getString(7));
            result.add(transaction);
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    return result;
}