Example usage for java.sql PreparedStatement setBoolean

List of usage examples for java.sql PreparedStatement setBoolean

Introduction

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

Prototype

void setBoolean(int parameterIndex, boolean x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java boolean value.

Usage

From source file:org.forumj.dbextreme.db.dao.FJThreadDao.java

public void close(Long threadId, boolean closed) throws IOException, ConfigurationException, SQLException {
    String query = getCloseThreadQuery();
    PreparedStatement st = null;
    Connection conn = null;//from   w  ww  .j  av a  2s.c o m
    try {
        conn = getConnection();
        st = conn.prepareStatement(query);
        st.setBoolean(1, closed);
        st.setLong(2, threadId);
        st.executeUpdate();
    } finally {
        readFinally(conn, st);
    }
}

From source file:dk.netarkivet.harvester.datamodel.GlobalCrawlerTrapListDBDAO.java

@Override
public int create(GlobalCrawlerTrapList trapList) {
    ArgumentNotValid.checkNotNull(trapList, "trapList");
    // Check for existence of a trapList in the database with the same name
    // and throw argumentNotValid if not
    if (exists(trapList.getName())) {
        throw new ArgumentNotValid(
                "Crawlertrap with name '" + trapList.getName() + "'already exists in database");
    }/*from   ww w  .j av a  2 s  .  c  om*/
    int trapId;
    Connection conn = HarvestDBConnection.get();
    PreparedStatement stmt = null;
    try {
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(INSERT_TRAPLIST_STMT, Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, trapList.getName());
        stmt.setString(2, trapList.getDescription());
        stmt.setBoolean(3, trapList.isActive());
        stmt.executeUpdate();
        ResultSet rs = stmt.getGeneratedKeys();
        rs.next();
        trapId = rs.getInt(1);
        trapList.setId(trapId);
        for (String expr : trapList.getTraps()) {
            stmt = conn.prepareStatement(INSERT_TRAP_EXPR_STMT);
            stmt.setInt(1, trapId);
            stmt.setString(2, expr);
            stmt.executeUpdate();
        }
        conn.commit();
    } catch (SQLException e) {
        String message = "SQL error creating global crawler trap list \n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stmt);
        DBUtils.rollbackIfNeeded(conn, "create trap list", trapList);
        HarvestDBConnection.release(conn);
    }
    return trapId;
}

From source file:org.cloudfoundry.identity.uaa.provider.JdbcIdentityProviderProvisioning.java

@Override
public IdentityProvider update(final IdentityProvider identityProvider) {
    validate(identityProvider);//from  ww w  .j  av a2  s  . c  o m
    final String zoneId = IdentityZoneHolder.get().getId();
    jdbcTemplate.update(UPDATE_IDENTITY_PROVIDER_SQL, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            int pos = 1;
            ps.setInt(pos++, identityProvider.getVersion() + 1);
            ps.setTimestamp(pos++, new Timestamp(new Date().getTime()));
            ps.setString(pos++, identityProvider.getName());
            ps.setString(pos++, identityProvider.getType());
            ps.setString(pos++, JsonUtils.writeValueAsString(identityProvider.getConfig()));
            ps.setBoolean(pos++, identityProvider.isActive());
            ps.setString(pos++, identityProvider.getId().trim());
            ps.setString(pos++, zoneId);
        }
    });
    return retrieve(identityProvider.getId());
}

From source file:com.concursive.connect.web.webdav.WebdavManager.java

/**
 * Description of the Method//w w  w.  j a va2  s.  c o  m
 *
 * @param db       Description of the Parameter
 * @param username Description of the Parameter
 * @param nonce    The feature to be added to the User attribute
 * @return Description of the Return Value
 * @throws SQLException Description of the Exception
 */
public boolean addUser(Connection db, String username, String nonce) throws SQLException {
    boolean status = false;
    PreparedStatement pst = db.prepareStatement("SELECT user_id, webdav_access, webdav_password "
            + "FROM users " + "WHERE username = ? " + "AND webdav_access = ? " + "AND enabled = ? ");
    pst.setString(1, username);
    pst.setBoolean(2, true);
    pst.setBoolean(3, true);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        //TODO: determine if the user account has not expired
        int userId = rs.getInt("user_id");
        int roleId = -1;
        String digest = rs.getString("webdav_password");
        WebdavUser user = new WebdavUser();
        user.setUserId(userId);
        user.setRoleId(roleId);
        user.setDigest(digest);
        user.setNonce(nonce);
        users.put(username, user);
        status = true;
    }
    rs.close();
    pst.close();
    return status;
}

From source file:mx.edu.um.escuela.dao.MaestroDaoJdbc.java

@Override
public Maestro crea(final Maestro maestro) {
    log.debug("Creando al maestro {}", maestro);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override/*ww w.jav a  2  s  .  c o m*/
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(CREAR_MAESTRO, new String[] { "id" });
            ps.setString(1, maestro.getNomina());
            ps.setString(2, maestro.getNombre());
            ps.setString(3, maestro.getApellido());
            if (maestro.getFechaNacimiento() != null) {
                ps.setDate(4, new java.sql.Date(maestro.getFechaNacimiento().getTime()));
            } else {
                ps.setNull(4, Types.DATE);
            }
            ps.setBoolean(5, maestro.getEsHombre());
            if (maestro.getCorreo() != null) {
                ps.setString(6, maestro.getCorreo());
            } else {
                ps.setNull(6, Types.VARCHAR);
            }
            return ps;
        }
    }, keyHolder);
    maestro.setId(keyHolder.getKey().longValue());

    maestros.add(maestro);
    return maestro;
}

From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java

public static synchronized RatingBean save(Connection db, int userId, int projectId, int objectId, String vote,
        String table, String uniqueField, int setInappropriateColumn) throws SQLException {
    boolean commit = false;
    try {//w  ww . java 2 s .c o  m
        commit = db.getAutoCommit();
        if (commit) {
            db.setAutoCommit(false);
        }
        // Determine the current value
        int existingVote = queryUserRating(db, userId, objectId, table, uniqueField);
        int newVote = Integer.parseInt(vote);
        PreparedStatement pst = null;
        ResultSet rs = null;
        // Determine if an update, insert, or delete is required
        if (existingVote == -1) {
            // Perform an insert
            pst = db.prepareStatement("INSERT INTO " + table + "_rating " + "(project_id, "
                    + (Project.PRIMARY_KEY.equals(uniqueField) ? "" : uniqueField + ", ")
                    + ((setInappropriateColumn != Constants.UNDEFINED) ? "inappropriate, " : "")
                    + "rating, enteredby) " + "VALUES (?, "
                    + (Project.PRIMARY_KEY.equals(uniqueField) ? "" : "?, ")
                    + ((setInappropriateColumn != Constants.UNDEFINED) ? "?, " : "") + "?, ?)");
            int i = 0;
            pst.setInt(++i, projectId);
            if (!Project.PRIMARY_KEY.equals(uniqueField)) {
                pst.setInt(++i, objectId);
            }
            if (setInappropriateColumn != Constants.UNDEFINED) {
                pst.setBoolean(++i, (setInappropriateColumn == Constants.TRUE));
            }
            pst.setInt(++i, newVote);
            pst.setInt(++i, userId);
            pst.execute();
            pst.close();
        } else if (existingVote != newVote) {
            // Try an update
            pst = db.prepareStatement("UPDATE " + table + "_rating " + "SET rating = ?, entered = "
                    + DatabaseUtils.getCurrentTimestamp(db) + " "
                    + ((setInappropriateColumn != Constants.UNDEFINED) ? ", inappropriate = ? " : "") + "WHERE "
                    + uniqueField + " = ? AND enteredby = ? ");
            int i = 0;
            pst.setInt(++i, newVote);
            if (setInappropriateColumn != Constants.UNDEFINED) {
                pst.setBoolean(++i, (setInappropriateColumn == Constants.TRUE));
            }
            pst.setInt(++i, objectId);
            pst.setInt(++i, userId);
            pst.execute();
            pst.close();
        }
        if (existingVote != newVote) {
            // Update the object count and value
            pst = db.prepareStatement("UPDATE " + table + " "
                    + "SET rating_count = rating_count + ?, rating_value = rating_value + ?, "
                    + "rating_avg = ((rating_value + ?) / (rating_count + ?)) " + "WHERE " + uniqueField
                    + " = ? ");
            int i = 0;
            if (existingVote == -1) {
                if (newVote == INAPPROPRIATE_COMMENT) {
                    //rating count is incremented, but no change in rating value, therefore, rating average decreases
                    pst.setInt(++i, 1);
                    pst.setInt(++i, 0);
                    pst.setInt(++i, 0);
                    pst.setInt(++i, 1);
                } else {
                    pst.setInt(++i, 1);
                    pst.setInt(++i, newVote);
                    pst.setInt(++i, newVote);
                    pst.setInt(++i, 1);
                }
            } else {
                if (newVote == INAPPROPRIATE_COMMENT || existingVote == INAPPROPRIATE_COMMENT) {
                    if (newVote == INAPPROPRIATE_COMMENT) {
                        //The effects of the previous rating are reversed.
                        pst.setInt(++i, 0);
                        pst.setInt(++i, (-1) * existingVote);
                        pst.setInt(++i, (-1) * existingVote);
                        pst.setInt(++i, 0);
                    } else if (existingVote == INAPPROPRIATE_COMMENT) {
                        //The new rating by the user is recorded,
                        //as an existing inappropriate comment was never considered towards rating value, no additional math is required
                        pst.setInt(++i, 0);
                        pst.setInt(++i, newVote);
                        pst.setInt(++i, newVote);
                        pst.setInt(++i, 0);
                    }
                } else {
                    pst.setInt(++i, 0);
                    pst.setInt(++i, newVote - existingVote);
                    pst.setInt(++i, newVote - existingVote);
                    pst.setInt(++i, 0);
                }
            }
            pst.setInt(++i, objectId);
            //System.out.println(pst);
            pst.execute();
            pst.close();
        }

        if (setInappropriateColumn != Constants.UNDEFINED) {
            int inappropriateCount = 0;
            pst = db.prepareStatement("SELECT count(*) AS ic " + "FROM " + table + "_rating " + "WHERE "
                    + uniqueField + " = ? AND inappropriate = ?");
            int i = 0;
            pst.setInt(++i, objectId);
            pst.setBoolean(++i, true);
            rs = pst.executeQuery();
            if (rs.next()) {
                inappropriateCount = rs.getInt("ic");
            }
            rs.close();
            pst.close();

            pst = db.prepareStatement("UPDATE " + table + " " + "SET  inappropriate_count = ? " + "WHERE "
                    + uniqueField + " = ? ");
            i = 0;
            pst.setInt(++i, inappropriateCount);
            pst.setInt(++i, objectId);
            pst.execute();
            pst.close();
        }

        // Retrieve the values
        pst = db.prepareStatement(
                "SELECT rating_count, rating_value " + "FROM " + table + " WHERE " + uniqueField + " = ?");
        pst.setInt(1, objectId);
        rs = pst.executeQuery();
        int count = 0;
        int value = 0;
        if (rs.next()) {
            count = rs.getInt("rating_count");
            value = rs.getInt("rating_value");
        }
        rs.close();
        pst.close();
        if (commit) {
            db.commit();
        }
        // Share the rating bean
        RatingBean rating = new RatingBean();
        rating.setItemId(objectId);
        rating.setCount(count);
        rating.setValue(value);
        return rating;
    } catch (Exception e) {
        if (commit) {
            db.rollback();
        }
        LOG.error("save", e);
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
}

From source file:dk.netarkivet.harvester.datamodel.GlobalCrawlerTrapListDBDAO.java

@Override
public List<String> getAllActiveTrapExpressions() {
    Connection conn = HarvestDBConnection.get();
    List<String> result = new ArrayList<String>();
    PreparedStatement stmt = null;
    try {//  www . j a  v  a 2  s .co m
        stmt = conn.prepareStatement("SELECT DISTINCT trap_expression " + "FROM global_crawler_trap_lists, "
                + "global_crawler_trap_expressions " + "WHERE global_crawler_trap_list_id = "
                + "crawler_trap_list_id " + "AND isActive = ?");
        stmt.setBoolean(1, true);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            result.add(rs.getString(1));
        }
        return result;
    } catch (SQLException e) {
        String message = "Error retrieving expressions.\n" + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stmt);
        HarvestDBConnection.release(conn);
    }
}

From source file:org.osaf.cosmo.migrate.ZeroPointFiveToZeroPointSixMigration.java

public void migrateData(Connection conn, String dialect) throws Exception {

    log.debug("starting migrateData()");

    // set isActive=true for all items
    PreparedStatement stmt = conn.prepareStatement("update item set isactive=?");
    stmt.setBoolean(1, true);
    int updated = stmt.executeUpdate();

    log.debug("updated " + updated + " item rows");

    migrateUsers(conn);/*from ww  w .j  a va2 s.c  o m*/
    migrateItems(conn);
    migrateAttributes(conn);
    migrateCalendarCollections(conn, dialect);
    migrateEvents(conn, dialect);
    migrateStamps(conn, dialect);
}

From source file:edu.jhu.pha.vospace.meta.MySQLMetaStore2.java

@Override
public void markRemoved(final VospaceId identifier, final boolean isRemoved) {
    if (identifier.getNodePath().isRoot(false))
        return;/*from  w w  w .  j a va  2  s  . com*/
    DbPoolServlet.goSql("Marking node as removed", "update nodes set deleted = ? " + "WHERE node_id = "
            + "(SELECT * FROM (SELECT nodes.node_id FROM nodes JOIN containers "
            + "ON nodes.container_id = containers.container_id JOIN user_identities "
            + "ON containers.user_id = user_identities.user_id WHERE `container_name` = ? AND `path` = ? AND `identity` = ?) a)",
            new SqlWorker<Integer>() {
                @Override
                public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                    stmt.setBoolean(1, isRemoved);
                    stmt.setString(2, identifier.getNodePath().getContainerName());
                    stmt.setString(3, identifier.getNodePath().getNodeRelativeStoragePath());
                    stmt.setString(4, owner);
                    return stmt.executeUpdate();
                }
            });
}

From source file:com.flexive.core.Database.java

/**
 * Store a FxString in a translation table that only consists of one(!) translation column
 *
 * @param string     string to be stored
 * @param con        existing connection
 * @param table      storage table//  w  w  w .  java 2 s.co m
 * @param dataColumn name of the data column
 * @param idColumn   name of the id column
 * @param id         id of the given string
 * @throws SQLException if a database error occured
 */
public static void storeFxString(FxString string, Connection con, String table, String dataColumn,
        String idColumn, long id) throws SQLException {
    if (!string.isMultiLanguage()) {
        throw new FxInvalidParameterException("string", LOG, "ex.db.fxString.store.multilang", table)
                .asRuntimeException();
    }
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement("DELETE FROM " + table + ML + " WHERE " + idColumn + "=?");
        ps.setLong(1, id);
        ps.execute();
        ps.close();
        if (string.getTranslatedLanguages().length > 0) {
            ps = con.prepareStatement("INSERT INTO " + table + ML + " (" + idColumn + ",LANG,DEFLANG,"
                    + dataColumn + ") VALUES (?,?,?,?)");
            ps.setLong(1, id);
            String curr;
            for (long lang : string.getTranslatedLanguages()) {
                curr = string.getTranslation(lang);
                if (curr != null && curr.trim().length() > 0) {
                    ps.setInt(2, (int) lang);
                    ps.setBoolean(3, lang == string.getDefaultLanguage());
                    ps.setString(4, curr);
                    ps.executeUpdate();
                }
            }
        }
    } finally {
        if (ps != null)
            ps.close();
    }
}