Example usage for java.sql PreparedStatement setInt

List of usage examples for java.sql PreparedStatement setInt

Introduction

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

Prototype

void setInt(int parameterIndex, int x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java int value.

Usage

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

public boolean save(final Connection conn, final SaveContext ctx) throws SQLException, DispatchException {
    final IErrorList<Integer> errors = ctx.getErrorList();
    if (ctx.getPrivilegeIds().containsKey(getName())) {
        if (log.isDebugEnabled())
            log.debug("role '" + getName() + "' is already defined as a privilege");
        errors.add(name.getRow(), "name", CommonServerErrors.DUPLICATE_ENTRY);
        return false;
    }//from   w  ww . ja va2  s .co  m
    Integer roleId = ctx.getRoleIds().get(getName());
    if (roleId != null) {
        if (ctx.getOption() == SqlInsertOptions.APPEND) {
            if (log.isDebugEnabled())
                log.debug("skipping role '" + getName() + "' (already defined)");
            return true;
        }
        // nothing to update for the actual role record
        // but clear definition before replacing it with new definition
        Database.executeUpdate(conn, "DELETE FROM role_definition WHERE role_id=?;", roleId);
    } else {
        if (log.isDebugEnabled())
            log.debug("adding role '" + getName() + "'");
        roleId = Database.addRecord(conn, "INSERT INTO role (name,uname) VALUES(?,?);", getName(),
                getName().toUpperCase());
        if (roleId == null)
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to insert role '" + getName() + "'"));
        ctx.getRoleIds().put(getName(), roleId);
    }
    if (definition == null || definition.isEmpty())
        return true;
    if (log.isDebugEnabled())
        log.debug("saving role definition for '" + getName() + "'");
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO role_definition (role_id, child_role_id) VALUES(?,?);");
    try {
        stmt.setInt(1, roleId);
        boolean success = true;
        for (XmlRoleName role : definition) {
            final Integer id = ctx.getRoleIds().get(role.getValue());
            if (id == null) {
                errors.add(role.getRow(), XmlRoleName.FIELD, CommonServerErrors.INVALID_VALUE);
                success = false;
            } else {
                stmt.setInt(2, id);
                stmt.addBatch();
            }
        }
        if (success && !Database.isBatchCompleted(stmt.executeBatch()))
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to insert role definition"));
        return success;
    } finally {
        Database.close(stmt);
    }
}

From source file:dhbw.clippinggorilla.objects.user.UserUtils.java

private static void setNewActivationKey(User u) {
    try {//from  w  w w.  ja  v a2  s.  c  o  m
        u.setActivationKey(getRandomIntAsString(6));
        String sql = "UPDATE " + Tables.USER + " SET " + Columns.ACTIVATION_KEY + " = ? WHERE " + Columns.ID
                + " = ?";
        PreparedStatement statement = Database.getConnection().prepareStatement(sql);
        statement.setString(1, u.getActivationKey());
        statement.setInt(2, u.getId());
        statement.executeUpdate();
    } catch (SQLException ex) {
        Log.warning("activationKey upload failed: ", ex);
    }
}

From source file:fll.web.playoff.Playoff.java

/**
 * Determine the playoff bracket number given a team number and performance
 * run number (1-based).//w w  w.j a v a  2  s.  c o  m
 * 
 * @param connection the database connection
 * @param tournamentId id of the tournament
 * @param teamNumber the team
 * @param runNumber the run
 * @return the bracket number or -1 if the bracket cannot be determined
 * @throws SQLException if a database error occurs
 */
public static int getBracketNumber(final Connection connection, final int tournamentId, final int teamNumber,
        final int runNumber) throws SQLException {
    PreparedStatement prep = null;
    ResultSet rs = null;
    try {
        prep = connection.prepareStatement("SELECT LineNumber FROM PlayoffData"//
                + " WHERE Team = ? " //
                + " AND run_number = ?" + " AND tournament = ?");
        prep.setInt(1, teamNumber);
        prep.setInt(2, runNumber);
        prep.setInt(3, tournamentId);
        rs = prep.executeQuery();
        if (rs.next()) {
            final int lineNumber = rs.getInt(1);
            // Always want to round up
            final int bracket = (lineNumber + 1) / 2;
            return bracket;
        } else {
            return -1;
        }
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(prep);
    }
}

From source file:org.obiba.onyx.jade.instrument.reichert.OraInstrumentRunner.java

private Map<String, Data> extractData(final String eyeSide) {
    return jdbc.query("select * from Measures where PatientId = ? and Eye = ? order by MeasureDate desc",
            new PreparedStatementSetter() {

                @Override//from w w w.j a v a2  s .c o  m
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setInt(1, extractPatientId());
                    ps.setString(2, eyeSide);
                }

            }, new ResultSetExtractor<Map<String, Data>>() {

                @Override
                public Map<String, Data> extractData(ResultSet rs) throws SQLException, DataAccessException {

                    // how to avoid while() ? last() on Access DB can not be called
                    log.info("Retrieve measures");
                    if (rs.next()) {
                        Putter data = new Putter(rs);
                        data.putInt("MeasureID");
                        data.putInt("MeasureNumber");
                        data.putDate("MeasureDate");
                        data.putDate("SessionDate");
                        data.putString("Eye");
                        data.putString("ORASerialNumber");
                        data.putString("ORASoftware");
                        data.putString("PCSoftware");
                        data.putDecimal("IOPG");
                        data.putDecimal("IOPCC");
                        data.putDecimal("CRF");
                        data.putDecimal("CCTAvg");
                        data.putDecimal("CCTLowest");
                        data.putDecimal("CCTSD");
                        data.putDecimal("CH");
                        data.putDecimal("TearFilmValue");
                        data.putString("Pressure");
                        data.putString("Applanation");
                        data.putDecimal("TimeIn");
                        data.putDecimal("TimeOut");
                        data.putString("Meds");
                        data.putString("Conditions");
                        data.putString("Notes1");
                        data.putString("Notes2");
                        data.putString("Notes3");
                        data.putDecimal("m_G2");
                        data.putDecimal("b_G2");
                        data.putDecimal("m_G3");
                        data.putDecimal("b_G3");
                        data.putDecimal("iop_cc_coef");
                        data.putDecimal("crf_coef");
                        data.putDecimal("m_ABC");
                        data.putDecimal("b_ABC");
                        data.putDecimal("b_PP");
                        data.putBoolean("BestWeighted");
                        data.putDecimal("QualityIndex");
                        data.putString("Indexes");
                        return data.getData();
                    }
                    return Collections.emptyMap();
                }
            });
}

From source file:fll.web.playoff.Playoff.java

/**
 * Given a team, get the playoff brackets that the team is associated with.
 * /*from ww w .  j a  v a  2  s. c  o m*/
 * @return the brackets, may be an empty list
 */
public static List<String> getPlayoffBracketsForTeam(final Connection connection, final int teamNumber)
        throws SQLException {
    final List<String> ret = new LinkedList<String>();
    final int tournament = Queries.getCurrentTournament(connection);
    PreparedStatement prep = null;
    ResultSet rs = null;
    try {
        prep = connection
                .prepareStatement("SELECT bracket_name FROM playoff_bracket_teams" + " WHERE team_number = ?"//
                        + " AND tournament_id = ?");
        prep.setInt(1, teamNumber);
        prep.setInt(2, tournament);
        rs = prep.executeQuery();
        while (rs.next()) {
            final String bracket = rs.getString(1);
            ret.add(bracket);
        }
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(prep);
    }
    return ret;
}

From source file:org.openmrs.module.openhmis.plm.db.DatabaseListProvider.java

/**
 * Removes the specified item from the list.
 * @param item The item to remove.//w w  w  .  j a  v  a2s.  c  o  m
 * @return {@code true} if the item was removed; otherwise, {@code false}.
 */
@Override
public boolean remove(final PersistentListItemModel item) {
    Session session = sessionFactory.getCurrentSession();
    Transaction trans = null;

    try {
        // Start transaction
        trans = session.beginTransaction();

        // Delete item with index
        session.delete(item);
        session.flush();

        // Update all items >= index to be their current index - 1
        // TODO: Can this type of query be handled by Hibernate without needing to use hardcoded SQL?
        session.doWork(new Work() {
            public void execute(Connection connection) {
                try {
                    PreparedStatement cmd = connection.prepareStatement(REMOVE_SQL);
                    cmd.setInt(1, item.getListId());
                    cmd.setInt(2, item.getItemOrder());

                    cmd.executeUpdate();
                } catch (SQLException sex) {
                    throw new PersistentListException(sex);
                }
            }
        });

        // Commit transaction
        trans.commit();
    } catch (Exception ex) {
        log.error("The list item delete operation failed.  Rolling back transaction...", ex);
        trans.rollback();
        log.debug("Transaction rolled back.");

        throw new PersistentListException(
                "An exception occurred while attempting to delete the item from the list.", ex);
    } finally {
        session.close();
    }

    return true;
}

From source file:dhbw.clippinggorilla.objects.user.UserUtils.java

/**
 * Changes email (requires two times the new email)
 *
 * @param u The User whose password should be changed
 * @param oldEmail The old mail//from  w  w  w .j  a  v  a2 s  .  c o m
 * @param newEmail The new mail
 * @param newEmail2 The new mail again to verify integrity
 * @return true: everything is ok, false: sth. went wrong
 */
public static synchronized boolean changeEmail(User u, String oldEmail, String newEmail, String newEmail2) {
    if (!newEmail.equals(oldEmail) && checkEmail(newEmail).length() == 0
            && checkSecondEmail(newEmail, newEmail2).length() == 0) {
        try {
            String sql = "UPDATE " + Tables.USER + " SET " + Columns.EMAIL + " = ? WHERE " + Columns.ID
                    + " = ?";
            PreparedStatement statement = Database.getConnection().prepareStatement(sql);
            statement.setString(1, newEmail);
            statement.setInt(2, u.getId());
            statement.executeUpdate();
            u.setEmail(newEmail);
            return true;
        } catch (SQLException ex) {
            Log.warning("Failed to change first name!", ex);
            return false;
        }
    }
    return false;
}

From source file:fll.web.playoff.Playoff.java

/**
 * Given a team and run number, get the playoff division
 * //from  w  w  w.  j  av  a 2  s. co  m
 * @param runNumber the performance run number
 * @return the division or null if not found
 */
public static String getPlayoffDivision(final Connection connection, final int teamNumber, final int runNumber)
        throws SQLException {
    final int tournament = Queries.getCurrentTournament(connection);
    PreparedStatement prep = null;
    ResultSet rs = null;
    try {
        prep = connection.prepareStatement("SELECT event_division FROM PlayoffData" + " WHERE Team = ?"//
                + " AND run_number = ?" //
                + " AND Tournament = ?");
        prep.setInt(1, teamNumber);
        prep.setInt(2, runNumber);
        prep.setInt(3, tournament);
        rs = prep.executeQuery();
        if (rs.next()) {
            final String division = rs.getString(1);
            return division;
        } else {
            return null;
        }
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(prep);
    }
}

From source file:com.sg.capstone.dao.BlogDaoDbImpl.java

private void insertBlogPostTags(BlogPost blogPost) {
    final int blogPostId = blogPost.getBlogPostId();
    final ArrayList<Integer> tagIds = blogPost.getTagIds();

    jdbcTemplate.batchUpdate(SQL_INSERT_BLOGPOST_TAGS, new BatchPreparedStatementSetter() {
        @Override//from  w w  w  .  j  av  a 2 s .  c  o m
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setInt(1, blogPostId);
            ps.setInt(2, tagIds.get(i));
        }

        @Override
        public int getBatchSize() {
            return tagIds.size();
        }
    });
}

From source file:com.sg.capstone.dao.BlogDaoDbImpl.java

private void insertBlogPostCategories(BlogPost blogPost) {
    final int blogPostId = blogPost.getBlogPostId();
    final ArrayList<Integer> categoryIds = blogPost.getCategoryIds();

    jdbcTemplate.batchUpdate(SQL_INSERT_BLOGPOST_CATEGORIES, new BatchPreparedStatementSetter() {
        @Override/*www  .jav  a  2s  .c  om*/
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setInt(1, blogPostId);
            ps.setInt(2, categoryIds.get(i));
        }

        @Override
        public int getBatchSize() {
            return categoryIds.size();
        }
    });
}