Example usage for java.sql PreparedStatement setDate

List of usage examples for java.sql PreparedStatement setDate

Introduction

In this page you can find the example usage for java.sql PreparedStatement setDate.

Prototype

void setDate(int parameterIndex, java.sql.Date x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

Usage

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateMilestoneGanttItems(final List<MilestoneGanttItem> milestoneGanttItems,
        Integer sAccountId) {/*  w  ww .j a  v a2 s . c o m*/
    if (CollectionUtils.isNotEmpty(milestoneGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-milestone-service" + sAccountId);
        try {
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement preparedStatement = connection.prepareStatement(
                            "UPDATE `m_prj_milestone` SET " + "name = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `owner`=?, `ganttIndex`=? WHERE `id` = ?");
                    for (int i = 0; i < milestoneGanttItems.size(); i++) {
                        preparedStatement.setString(1, milestoneGanttItems.get(i).getName());
                        preparedStatement.setDate(2,
                                getDateWithNullValue(milestoneGanttItems.get(i).getStartDate()));
                        preparedStatement.setDate(3,
                                getDateWithNullValue(milestoneGanttItems.get(i).getEndDate()));
                        preparedStatement.setDate(4, new Date(now));
                        preparedStatement.setString(5, milestoneGanttItems.get(i).getAssignUser());
                        preparedStatement.setInt(6, milestoneGanttItems.get(i).getGanttIndex());
                        preparedStatement.setInt(7, milestoneGanttItems.get(i).getId());
                        preparedStatement.addBatch();

                    }
                    preparedStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-milestone-service" + sAccountId);
            lock.unlock();
        }
    }
}

From source file:org.apache.phoenix.end2end.index.IndexMaintenanceIT.java

/**
 * Adds a row to the index data table/* w  w  w  .  j a  v a 2  s  . co  m*/
 * 
 * @param i
 *            row number
 */
private void insertRow(PreparedStatement stmt, int i) throws SQLException {
    // insert row
    stmt.setString(1, "varchar" + String.valueOf(i));
    stmt.setString(2, "char" + String.valueOf(i));
    stmt.setInt(3, i);
    stmt.setLong(4, i);
    stmt.setBigDecimal(5, new BigDecimal(i * 0.5d));
    Date date = new Date(DateUtil.parseDate("2015-01-01 00:00:00").getTime() + (i - 1) * MILLIS_IN_DAY);
    stmt.setDate(6, date);
    stmt.setString(7, "a.varchar" + String.valueOf(i));
    stmt.setString(8, "a.char" + String.valueOf(i));
    stmt.setInt(9, i);
    stmt.setLong(10, i);
    stmt.setBigDecimal(11, new BigDecimal(i * 0.5d));
    stmt.setDate(12, date);
    stmt.setString(13, "b.varchar" + String.valueOf(i));
    stmt.setString(14, "b.char" + String.valueOf(i));
    stmt.setInt(15, i);
    stmt.setLong(16, i);
    stmt.setBigDecimal(17, new BigDecimal(i * 0.5d));
    stmt.setDate(18, date);
    stmt.executeUpdate();
}

From source file:com.oic.event.RegisterProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;//  ww w  .  j  av  a  2s .c  om
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "INSERT INTO user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ?, secretkey = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setString(8, json.get("secretkey").toString());
        ps.executeUpdate();
        ps.close();

        sql = "SELECT last_insert_id() AS last";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            throw new SQLException();
        }
        long userid = rs.getLong("last");
        rs.close();
        ps.close();

        sql = "INSERT INTO setting SET userid = ?, privategrade = ?, privatesex = ?, privatebirth = ?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, userid);
        ps.setInt(2, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(4, Integer.parseInt(json.get("vbirthday").toString()));
        ps.executeUpdate();
        ps.close();
        con.commit();

        responseJSON.put("status", 0);
        webSocket.userNoLogin();
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }
    webSocket.sendJson(responseJSON);
}

From source file:com.oic.event.SetProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;/*from w  w  w. j  a  va  2 s  . c o  m*/
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "UPDATE user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ? "
                + "WHERE userid = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setLong(8, webSocket.getCharacter().getUserId());
        ps.executeUpdate();
        ps.close();

        sql = "UPDATE setting SET privategrade = ?, privatesex = ?, privatebirth =? WHERE userid = ?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(2, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vbirthday").toString()));
        ps.setLong(4, webSocket.getCharacter().getUserId());

        ps.executeUpdate();
        ps.close();

        con.commit();

        //TODO 
        responseJSON.put("status", 0);
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }

    webSocket.sendJson(responseJSON);
}

From source file:gov.nih.nci.cadsr.persist.de.Data_Elements_Mgr.java

/**
 * Deletes single row of Data Element//from   w w  w . j a  v a 2s  .c o m
 * 
 * @param de_IDSEQ
 * @param modified_by
 * @param conn
 * @throws DBException
 */
public void delete(String idseq, String modified_by, Connection conn) throws DBException {
    PreparedStatement statement = null;

    try {

        String sql = "update data_elements_view set deleted_ind = ?, modified_by = ?,date_modified = ? where de_idseq = ? ";

        int column = 0;
        statement = conn.prepareStatement(sql);
        statement.setString(++column, DBConstants.RECORD_DELETED_YES);
        statement.setString(++column, modified_by);
        statement.setDate(++column, new java.sql.Date(new java.util.Date().getTime()));
        statement.setString(++column, idseq);

        int code = statement.executeUpdate();
        if (code < 0) {
            throw new Exception("Unable to delete the DE");
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Deleted DE");
            }
        }
    } catch (Exception e) {
        logger.error("Error deleting Data Element " + idseq + e);
        errorList.add(DeErrorCodes.API_DE_502);
        throw new DBException(errorList);
    } finally {
        statement = SQLHelper.closePreparedStatement(statement);
    }

}

From source file:netflow.DatabaseProxy.java

private void updateAggregationResults(List<AggregationRecord> records) throws SQLException {
    if (records.isEmpty()) {
        log.debug("Nothing to update");
        return;/* ww w . jav  a2  s.com*/
    }
    log.debug("updateAggregationResults(): <<<<");
    log.debug(records.size() + " to update");
    PreparedStatement pstmt = con.prepareStatement(getQuery("aggregation.summary.update"));
    for (AggregationRecord record : records) {
        pstmt.setLong(1, record.getInput());
        pstmt.setLong(2, record.getOutput());
        pstmt.setInt(3, record.getClientId());
        pstmt.setDate(4, record.getDate());
        pstmt.addBatch();
    }
    final int[] ints = pstmt.executeBatch();
    log.debug(ints.length + " records updated");
    log.debug("updateAggregationResults(): >>>>");

}

From source file:netflow.DatabaseProxy.java

private void addAggregationResults(List<AggregationRecord> records) throws SQLException {
    if (records.isEmpty()) {
        log.debug("Nothing to insert");
        return;/*from   w  w  w .ja  v  a2s  .  co m*/
    }

    log.debug("insertAggregationResults(): <<<<");
    log.debug(records.size() + " to insert");
    PreparedStatement pstmt = con.prepareStatement(getQuery("aggregation.summary.insert"));
    for (AggregationRecord record : records) {
        pstmt.setLong(1, record.getInput());
        pstmt.setLong(2, record.getOutput());
        pstmt.setInt(3, record.getClientId());
        pstmt.setDate(4, record.getDate());
        pstmt.addBatch();
    }
    final int[] ints = pstmt.executeBatch();
    log.debug(ints.length + " records inserted");
    log.debug("insertAggregationResults(): >>>>");
}

From source file:nl.tudelft.stocktrader.derby.DerbyOrderDAO.java

public int createHolding(Order order) throws DAOException {
    if (logger.isDebugEnabled()) {
        logger.debug("OrderDAO.createHolding(OrderDataModel)\nOrderID :" + order.getOrderID() + "\nOrderType :"
                + order.getOrderType() + "\nSymbol :" + order.getSymbol() + "\nQuantity :" + order.getQuantity()
                + "\nOrder Status :" + order.getOrderStatus() + "\nOrder Open Date :" + order.getOpenDate()
                + "\nCompletionDate :" + order.getCompletionDate());
    }//  w w w.jav a  2s. c o  m

    PreparedStatement getAccountIdStat = null;
    int accountId = -1;

    try {
        getAccountIdStat = sqlConnection.prepareStatement(SQL_GET_ACCOUNTID_ORDER);
        getAccountIdStat.setInt(1, order.getOrderID());

        ResultSet rs = getAccountIdStat.executeQuery();
        if (rs.next()) {
            accountId = Integer.parseInt(rs.getString(1));
            order.setAccountId(accountId);
        }

        try {
            rs.close();
        } catch (Exception e) {
            logger.debug("", e);
        }
    } catch (SQLException e) {
        throw new DAOException(
                "Exception is thrown when selecting the accountID from order entries where order ID :"
                        + order.getOrderID(),
                e);

    } finally {
        if (getAccountIdStat != null) {
            try {
                getAccountIdStat.close();
            } catch (Exception e) {
                logger.debug("", e);
            }
        }
    }

    if (accountId != -1) {
        int holdingId = -1;
        PreparedStatement insertHoldingStat = null;

        try {
            insertHoldingStat = sqlConnection.prepareStatement(SQL_INSERT_HOLDING);
            insertHoldingStat.setBigDecimal(1, order.getPrice());
            insertHoldingStat.setDouble(2, order.getQuantity());
            Calendar openDate = (order.getOpenDate() != null) ? order.getOpenDate() : Calendar.getInstance();
            insertHoldingStat.setDate(3, StockTraderUtility.convertToSqlDate(openDate));
            insertHoldingStat.setInt(4, order.getAccountId());
            insertHoldingStat.setString(5, order.getSymbol());
            insertHoldingStat.executeUpdate();

            ResultSet rs = sqlConnection.prepareCall(SQL_GET_LAST_INSERT_ID).executeQuery();
            if (rs.next()) {
                holdingId = rs.getInt(1);
            }

            try {
                rs.close();
            } catch (Exception e) {
                logger.debug("", e);
            }
            return holdingId;

        } catch (SQLException e) {
            throw new DAOException("An exception is thrown during an insertion of a holding entry", e);

        } finally {
            if (insertHoldingStat != null) {
                try {
                    insertHoldingStat.close();
                } catch (Exception e) {
                    logger.debug("", e);
                }
            }
        }
    }
    return -1;
}

From source file:com.nabla.dc.server.xml.settings.XmlCompany.java

public boolean save(final Connection conn, final Map<String, Integer> companyIds, final SaveContext ctx)
        throws SQLException, DispatchException {
    Integer companyId = companyIds.get(getName());
    if (companyId != null) {
        if (ctx.getOption() == SqlInsertOptions.APPEND)
            return true;
        Database.executeUpdate(conn, "UPDATE company SET active=? WHERE id=?;", active, companyId);
        Database.executeUpdate(conn, "DELETE FROM financial_year WHERE company_id=?;", companyId);
        if (accounts != null) {
            if (log.isDebugEnabled())
                log.debug("deleting all accounts of company '" + getName() + "'");
            accounts.clear(conn, companyId);
        }/*from w  ww  . ja  va 2s. c o m*/
        if (asset_categories != null)
            asset_categories.clear(conn, companyId);
        if (users != null)
            users.clear(conn, companyId);
    } else {
        companyId = Database.addRecord(conn, "INSERT INTO company (name,uname,active) VALUES(?,?,?);",
                getName(), getName().toUpperCase(), active);
        if (companyId == null)
            throw new InternalErrorException(Util.formatInternalErrorDescription("failed to insert company"));
        companyIds.put(getName(), companyId);
    }
    final Integer financialYearId = Database.addRecord(conn,
            "INSERT INTO financial_year (company_id, name) VALUES(?,?);", companyId, financial_year);
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO period_end (financial_year_id,name,end_date) VALUES(?,?,?);");
    try {
        stmt.setInt(1, financialYearId);
        final Calendar dt = new GregorianCalendar();
        dt.setTime(start_date);
        final SimpleDateFormat financialYearFormat = new SimpleDateFormat("MMM yyyy");
        for (int m = 0; m < 12; ++m) {
            dt.set(GregorianCalendar.DAY_OF_MONTH, dt.getActualMaximum(GregorianCalendar.DAY_OF_MONTH));
            final Date end = new Date(dt.getTime().getTime());
            stmt.setString(2, financialYearFormat.format(end));
            stmt.setDate(3, end);
            stmt.addBatch();
            dt.add(GregorianCalendar.MONTH, 1);
        }
        if (!Database.isBatchCompleted(stmt.executeBatch()))
            throw new InternalErrorException(Util
                    .formatInternalErrorDescription("fail to insert periods for company '" + getName() + "'"));
    } finally {
        stmt.close();
    }
    if (accounts != null)
        accounts.save(conn, companyId);
    return (asset_categories == null || asset_categories.save(conn, companyId, ctx))
            && (users == null || users.save(conn, companyId, ctx));
}

From source file:io.github.sislivros.persistencia.UsuarioBdDao.java

@Override
public boolean salvar(Usuario usuario) {

    try {//from   w ww  .  j  a  v  a  2s .  c  o  m

        if (getConnection() == null || getConnection().isClosed()) {
            conectar();
        }

        String sql = "INSERT INTO usuario (email, senha, apelido, data_nascimento, "
                + "cidade, estado, nome, foto_perfil, foto_capa, tipo, data_cadastro) "
                + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = getConnection().prepareStatement(sql);
        Date dataNascimento = null;
        if (usuario.getDataNascimento() != null) {
            dataNascimento = new Date(usuario.getDataNascimento().getTime());
        }

        ps.setString(1, usuario.getEmail());
        ps.setString(2, DigestUtils.sha1Hex(usuario.getSenha()));
        ps.setString(3, usuario.getApelido());
        ps.setDate(4, dataNascimento);
        ps.setString(5, usuario.getCidade());
        ps.setString(6, usuario.getEstado());
        ps.setString(7, usuario.getNome());
        ps.setString(8, usuario.getFotoPerfil());
        ps.setString(9, usuario.getFotoCapa());
        ps.setInt(10, usuario.getTipo().id);
        ps.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
        ps.executeUpdate();

        TimeLineEvent timeLineEvent = new TimeLineEvent();
        timeLineEvent.setData(new Timestamp(System.currentTimeMillis()));
        timeLineEvent.setNome("Criou uma conta");
        timeLineEvent.setDescricao("Conta criada com sucesso !");
        timeLineEvent.setTipo(TimeLineEventType.CRIACAO_CONTA);
        timeLineEvent.setEmailUsuario(usuario.getEmail());

        TimeLineEventBdDao timeDao = new TimeLineEventBdDao();
        timeDao.salvar(timeLineEvent);

        return true;
    } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) {
        ex.printStackTrace();

        return false;
    } finally {
        desconectar();
    }
}