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:net.freechoice.model.orm.Map_Profile.java

@Override
public PreparedStatementCreator createUpdate(final FC_Profile entity) {

    return new PreparedStatementCreator() {

        @Override// w w w.j a  va2 s . co m
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {

            PreparedStatement ps = con.prepareStatement(
                    "update  FC_Transaction" + " set  id_user_ = ? " + ",      site_personal = ? "
                            + ",     name_first = ? " + ",     name_last = ? " + ",     contact_public = ? "
                            + ",     gender = ? " + ",     date_birth = ? " + " where id = ?");
            ps.setInt(1, entity.id_user_);
            ps.setString(2, entity.site_personal);
            ps.setString(3, entity.name_first);
            ps.setString(4, entity.name_last);
            ps.setString(5, entity.contact_public);
            ps.setBoolean(6, entity.gender);
            ps.setDate(7, entity.date_birth);
            ps.setInt(8, entity.id);
            return ps;
        }
    };
}

From source file:org.springframework.security.provisioning.JdbcUserDetailsManager.java

public void createUser(final UserDetails user) {
    validateUserDetails(user);/* ww w  . j a  v a2  s.  co  m*/

    getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setBoolean(3, user.isEnabled());

            int paramCount = ps.getParameterMetaData().getParameterCount();
            if (paramCount > 3) {
                //NOTE: acc_locked, acc_expired and creds_expired are also to be inserted
                ps.setBoolean(4, !user.isAccountNonLocked());
                ps.setBoolean(5, !user.isAccountNonExpired());
                ps.setBoolean(6, !user.isCredentialsNonExpired());
            }
        }
    });

    if (getEnableAuthorities()) {
        insertUserAuthorities(user);
    }
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public void disable(List<Penalty> list) {
    String sql = "update penalty set active = ? where id = ?";
    Connection conn = null;/*from w  w  w  .  j  a  v a  2s  .  c om*/
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        for (Penalty p : list) {
            st.setBoolean(1, false);
            st.setLong(2, p.getKey());
            st.addBatch();
        }
        st.executeBatch();
    } catch (SQLException e) {
        logger.error("disable: {}", e);
    } catch (IOException e) {
        logger.error("disable: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public List<Penalty> findExpired() {
    String sql = "select * from penalty where type = ? and duration > 0 and expires < CURRENT_TIMESTAMP and active = ?";
    Connection conn = null;//from   w  w  w.  ja va 2 s  .c om
    List<Penalty> list = new ArrayList<Penalty>();
    try {
        conn = ConnectionFactory.getSecondaryConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setInt(1, Penalty.BAN);
        st.setBoolean(2, true);
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            Penalty penalty = new Penalty();
            loadPenalty(penalty, rs);
            list.add(penalty);
        }
    } catch (SQLException e) {
        logger.error("findExpired: {}", e);
    } catch (IOException e) {
        logger.error("findExpired: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return list;
}

From source file:org.apache.ode.scheduler.simple.jdbc.SchedulerDAOConnectionImpl.java

public boolean updateJob(JobDAO job) throws DatabaseException {
    if (__log.isDebugEnabled())
        __log.debug("updateJob " + job.getJobId() + " retryCount=" + job.getDetails().getRetryCount());

    Connection con = null;//ww  w  .ja va2s  .  c  o  m
    PreparedStatement ps = null;
    try {
        con = getConnection();
        ps = con.prepareStatement(UPDATE_JOB);
        ps.setLong(1, job.getScheduledDate());
        ps.setInt(2, job.getDetails().getRetryCount());
        ps.setBoolean(3, job.isScheduled());
        ps.setString(4, job.getJobId());
        return ps.executeUpdate() == 1;
    } catch (SQLException se) {
        throw new DatabaseException(se);
    } finally {
        close(ps);
        close(con);
    }
}

From source file:org.tec.webapp.jdbc.entity.support.PreparedStatementBuilder.java

/**
 * Set a prepared statement field based on type
 *
 * @param stmt PrepapredStatement/*from w  w w. j  ava2s .c o m*/
 * @param index index of the parameter in the stmt
 * @param param the param value and metadata
 */
protected void setParameter(PreparedStatement stmt, int index, Parameter param) {
    try {
        if (param.getData() == null) {
            stmt.setNull(index, param.getType().getVendorTypeNumber());
        } else {
            switch (param.getType()) {
            case BOOLEAN:
                stmt.setBoolean(index, (Boolean) param.getData());
                break;
            case DATE:
                /*
                 * java.sql.Date date = TextHelper.parseDate(param.getData()); if
                 * (null == date) { throw new
                 * SQLException("failed to set parameter: stmt=" + stmt + " index="
                 * + index + " param=" + param); } stmt.setDate(index, date);
                 */
                break;
            case TIME:
                /*
                 * Time time = TextHelper.parseTime(param.getData()); if (null ==
                 * time) { throw new SQLException("failed to set parameter: stmt=" +
                 * stmt + " index=" + index + " param=" + param); }
                 * stmt.setTime(index, time);
                 */
                break;
            case TIMESTAMP:
                /*
                 * Timestamp ts = TextHelper.parseTimestamp(param.getData()); if
                 * (null == ts) { throw new
                 * SQLException("failed to set parameter: stmt=" + stmt + " index="
                 * + index + " param=" + param); } stmt.setTimestamp(index, ts);
                 */
                break;
            case INTEGER:
                if (param.getData() instanceof Long) {
                    Long l = (Long) param.getData();
                    stmt.setLong(index, l);
                } else {
                    Integer i = (Integer) param.getData();
                    stmt.setInt(index, i);
                }
                break;
            case FLOAT:
                Float f = (Float) param.getData();
                stmt.setFloat(index, f);
                break;
            default: // set string for non explicit types
                String tmp = StringUtils.replaceEachRepeatedly((String) param.getData(), INVALID_TEXT_CHARS,
                        CORRECT_TEXT_CHARS);
                stmt.setString(index, tmp);
                break;
            }
        }
    } catch (Throwable e) {
        throw new RuntimeException("failed to process parameter " + param, e);
    }
}

From source file:com.npstrandberg.simplemq.MessageQueueImp.java

public long messageCount() {
    long count = -1;

    try {//from   w ww  .ja  va 2s  .  c o  m
        PreparedStatement ps = conn.prepareStatement("SELECT COUNT(id) FROM message WHERE read=?");
        ps.setBoolean(1, false);

        ResultSet rs = ps.executeQuery();

        rs.next();
        count = rs.getLong(1);
        ps.close();
    } catch (SQLException e) {
        logger.error(e);
    }

    return count;
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSimple.java

/**
 * {@inheritDoc}/*from   ww  w  .  jav a 2  s .  co  m*/
 */
@Override
public FxTreeNodeInfo getTreeNodeInfo(Connection con, FxTreeMode mode, long nodeId)
        throws FxApplicationException {
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement(
                prepareSql(mode, mode == FxTreeMode.Live ? TREE_LIVE_NODEINFO : TREE_EDIT_NODEINFO));
        ps.setBoolean(1, mode == FxTreeMode.Live);
        ps.setLong(2, nodeId);
        ps.setBoolean(3, true);
        ResultSet rs = ps.executeQuery();
        if (rs == null || !rs.next())
            throw new FxNotFoundException("ex.tree.node.notFound", nodeId, mode);
        FxType _type = CacheAdmin.getEnvironment().getType(rs.getLong(15));
        long _stepACL = CacheAdmin.getEnvironment().getStep(rs.getLong(17)).getAclId();
        long _createdBy = rs.getLong(18);
        long _mandator = rs.getLong(19);
        final FxPK reference = new FxPK(rs.getLong(9), rs.getInt(16));
        final List<Long> aclIds = fetchNodeACLs(con, reference);
        return new FxTreeNodeInfoSimple(rs.getLong(1), rs.getLong(2), rs.getLong(5), rs.getLong(6),
                rs.getInt(4), rs.getInt(8), rs.getInt(7), rs.getLong(3), nodeId, rs.getString(12), reference,
                aclIds, mode, rs.getInt(13), rs.getString(10), rs.getLong(11),
                FxPermissionUtils.getPermissionUnion(aclIds, _type, _stepACL, _createdBy, _mandator));
    } catch (SQLException e) {
        throw new FxTreeException(e, "ex.tree.nodeInfo.sqlError", nodeId, e.getMessage());
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            LOG.error(e, e);
        }
    }
}

From source file:net.dv8tion.discord.commands.TodoCommand.java

private void handleLock(MessageReceivedEvent e, String[] args, boolean locked) throws SQLException {
    checkArgs(args, 2,//from w  ww.  ja va2  s  .c  o  m
            "No todo ListName was specified. Usage: `" + getAliases().get(0) + " lock/unlock [ListName]`");

    String label = args[2].toLowerCase();
    TodoList todoList = todoLists.get(label);
    if (todoList == null) {
        sendMessage(e, "Sorry, `" + label + "` isn't a known todo list.");
        return;
    }

    if (!todoList.isAuthUser(e.getAuthor())) {
        sendMessage(e, "Sorry, you do not have permission to lock or unlock the `" + label + "` todo list.");
        return;
    }

    PreparedStatement setTodoListLocked = Database.getInstance().getStatement(SET_TODO_LIST_LOCKED);
    setTodoListLocked.setBoolean(1, locked);
    setTodoListLocked.setInt(2, todoList.id);
    if (setTodoListLocked.executeUpdate() == 0)
        throw new SQLException(SET_TODO_LIST_LOCKED + " reported no updated rows!");
    setTodoListLocked.clearParameters();

    todoList.locked = locked;
    sendMessage(e, "The `" + label + "` todo list was `" + (locked ? "locked`" : "unlocked`"));
}

From source file:org.schedoscope.metascope.tasks.repository.mysql.impl.TableEntityMySQLRepository.java

public void insertOrUpdatePartial(Connection connection, List<TableEntity> tables) {
    String insertTableSql = "insert into table_entity (table_fqdn, table_name, database_name, url_path_prefix, external_table, "
            + "table_description, storage_format, materialize_once, transformation_type, status) "
            + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
            + "on duplicate key update table_fqdn=values(table_fqdn), table_name=values(table_name), database_name=values(database_name), "
            + "url_path_prefix=values(url_path_prefix),external_table=values(external_table), table_description=values(table_description), "
            + "storage_format=values(storage_format), materialize_once=values(materialize_once), transformation_type=values(transformation_type), "
            + "status=values(status)";
    PreparedStatement stmt = null;
    try {/* w w w .jav a2 s .  c om*/
        int batch = 0;
        connection.setAutoCommit(false);
        stmt = connection.prepareStatement(insertTableSql);
        for (TableEntity tableEntity : tables) {
            stmt.setString(1, tableEntity.getFqdn());
            stmt.setString(2, tableEntity.getTableName());
            stmt.setString(3, tableEntity.getDatabaseName());
            stmt.setString(4, tableEntity.getUrlPathPrefix());
            stmt.setBoolean(5, tableEntity.isExternalTable());
            stmt.setString(6, tableEntity.getTableDescription());
            stmt.setString(7, tableEntity.getStorageFormat());
            stmt.setBoolean(8, tableEntity.isMaterializeOnce());
            stmt.setString(9, tableEntity.getTransformationType());
            stmt.setString(10, tableEntity.getStatus());
            stmt.addBatch();
            batch++;
            if (batch % 1024 == 0) {
                stmt.executeBatch();
            }
        }
        stmt.executeBatch();
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        LOG.error("Could not save table", e);
    } finally {
        DbUtils.closeQuietly(stmt);
    }
}