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.apache.tajo.catalog.store.DBStore.java

public final void addIndex(final IndexDescProto proto) throws IOException {
    String sql = "INSERT INTO indexes (index_name, " + C_TABLE_ID + ", column_name, "
            + "data_type, index_type, is_unique, is_clustered, is_ascending) VALUES " + "(?,?,?,?,?,?,?,?)";

    PreparedStatement stmt = null;

    wlock.lock();//from  w  ww  .  j a  va 2 s  .  co  m
    try {
        stmt = conn.prepareStatement(sql);
        stmt.setString(1, proto.getName());
        stmt.setString(2, proto.getTableId());
        stmt.setString(3, proto.getColumn().getColumnName());
        stmt.setString(4, proto.getColumn().getDataType().getType().name());
        stmt.setString(5, proto.getIndexMethod().toString());
        stmt.setBoolean(6, proto.hasIsUnique() && proto.getIsUnique());
        stmt.setBoolean(7, proto.hasIsClustered() && proto.getIsClustered());
        stmt.setBoolean(8, proto.hasIsAscending() && proto.getIsAscending());
        stmt.executeUpdate();
        if (LOG.isDebugEnabled()) {
            LOG.debug(stmt.toString());
        }
    } catch (SQLException se) {
        throw new IOException(se);
    } finally {
        wlock.unlock();
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
        }
    }
}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

private void updateServiceTransaction(TransactionContext transactionContext, CompensableArchive holder) {
    Connection connection = null;
    PreparedStatement stmt = null;
    try {//from www . ja v a 2s  .c  o m
        connection = this.getConnection();

        StringBuilder ber = new StringBuilder();
        ber.append("update tcc_compensable set try_committed = ? ");
        ber.append(", confirmed = ?, cancelled = ?, committed = ?, rolledback = ? ");
        ber.append("where application = ? and endpoint = ? and global_tx_id = ? and branch_qualifier = ?");
        stmt = connection.prepareStatement(ber.toString());

        XidImpl internalXid = holder.branchXid;

        stmt.setBoolean(1, holder.tryCommitted);
        stmt.setBoolean(2, holder.confirmed);
        stmt.setBoolean(3, holder.cancelled);
        stmt.setBoolean(4, holder.committed);
        stmt.setBoolean(5, holder.rolledback);

        stmt.setString(6, this.instanceKey.getApplication());
        stmt.setString(7, this.instanceKey.getEndpoint());
        stmt.setString(8, ByteUtils.byteArrayToString(internalXid.getGlobalTransactionId()));
        if (transactionContext.isCoordinator()) {
            stmt.setString(9, TransactionLogger.NULL);
        } else {
            stmt.setString(9, ByteUtils.byteArrayToString(internalXid.getBranchQualifier()));
        }

        stmt.executeUpdate();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        closeStatement(stmt);
        this.releaseConnection(connection);
    }
}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

@Override
public void cleanupTransaction(TransactionArchive transaction) {
    Connection connection = null;
    PreparedStatement stmt = null;
    try {//from  w  ww.j a v a2s. com
        connection = this.getConnection();

        StringBuilder ber = new StringBuilder();
        ber.append("update tcc_transaction set deleted = ? ");
        ber.append("where application = ? and endpoint = ? and global_tx_id = ?");// and branch_qualifier = ?
        stmt = connection.prepareStatement(ber.toString());

        TransactionContext transactionContext = transaction.getTransactionContext();
        XidImpl globalXid = transactionContext.getGlobalXid();

        stmt.setBoolean(1, true);
        stmt.setString(2, this.instanceKey.getApplication());
        stmt.setString(3, this.instanceKey.getEndpoint());
        stmt.setString(4, ByteUtils.byteArrayToString(globalXid.getGlobalTransactionId()));

        stmt.executeUpdate();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        closeStatement(stmt);
        this.releaseConnection(connection);
    }
}

From source file:org.openmrs.util.databasechange.ConceptReferenceTermChangeSet.java

/**
 * Convenience method that inserts rows into the concept reference term table. The
 * concept_map_id values becomes the concept_reference_term_id values
 * /*from  w  ww  . j a va2s .c om*/
 * @param connection the current database connection
 * @param listOfPropertyValueMaps a list of property and value maps for the objects to insert
 * @throws CustomChangeException
 */
private void insertRows(JdbcConnection connection, List<Map<String, Object>> listOfPropertyValueMaps)
        throws CustomChangeException {
    if (CollectionUtils.isNotEmpty(listOfPropertyValueMaps)) {
        PreparedStatement pStmt = null;
        try {
            connection.setAutoCommit(false);
            pStmt = connection.prepareStatement("INSERT INTO concept_reference_term"
                    + "(concept_reference_term_id, concept_source_id, code, description, creator, date_created, retired, uuid) "
                    + "VALUES(?, ?, ?, ?, ?, ?, ?, ?)");

            for (Map<String, Object> propertyValueMap : listOfPropertyValueMaps) {
                pStmt.setInt(1, (Integer) propertyValueMap.get("termId"));
                pStmt.setInt(2, (Integer) propertyValueMap.get("sourceId"));
                pStmt.setString(3, propertyValueMap.get("code").toString());
                pStmt.setString(4, (propertyValueMap.get("description") == null) ? null
                        : propertyValueMap.get("description").toString());
                pStmt.setInt(5, (Integer) propertyValueMap.get("creator"));
                pStmt.setDate(6, (Date) propertyValueMap.get("dateCreated"));
                pStmt.setBoolean(7, false);
                pStmt.setString(8, propertyValueMap.get("uuid").toString());

                pStmt.addBatch();
            }

            try {
                int[] updateCounts = pStmt.executeBatch();
                for (int i = 0; i < updateCounts.length; i++) {
                    if (updateCounts[i] > -1) {
                        log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                    } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                        log.debug("Successfully executed; No Success info");
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to execute update");
                    }
                }

                log.debug("Committing updates...");
                connection.commit();
            } catch (BatchUpdateException be) {
                log.warn("Error generated while processsing batch update", be);
                int[] updateCounts = be.getUpdateCounts();

                for (int i = 0; i < updateCounts.length; i++) {
                    if (updateCounts[i] > -1) {
                        log.warn("Executed with exception: updateCount=" + updateCounts[i]);
                    } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                        log.warn("Executed with exception; No Success info");
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to execute update with exception");
                    }
                }

                try {
                    log.warn("Rolling back batch", be);
                    connection.rollback();
                } catch (Exception rbe) {
                    log.warn("Error generated while rolling back batch update", be);
                }

                //marks the changeset as a failed one
                throw new CustomChangeException(
                        "Failed to generate concept reference terms from existing concept mappings.");
            }
        } catch (DatabaseException e) {
            throw new CustomChangeException("Error generated", e);
        } catch (SQLException e) {
            throw new CustomChangeException("Error generated", e);
        } finally {
            //reset to auto commit mode
            try {
                connection.setAutoCommit(true);
            } catch (DatabaseException e) {
                log.warn("Failed to reset auto commit back to true", e);
            }

            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (SQLException e) {
                    log.warn("Failed to close the prepared statement object");
                }
            }
        }
    } else
        log.error("List of property value maps is null or empty");
}

From source file:org.apache.gora.sql.store.SqlStore.java

/**
 * Sets the object to the preparedStatement by it's schema
 *//*from  w w  w . ja  v  a 2 s .  co m*/
public void setObject(PreparedStatement statement, int index, Object object, Schema schema, Column column)
        throws SQLException, IOException {

    Type type = schema.getType();

    switch (type) {
    case MAP:
        setField(statement, column, schema, index, object);
        break;
    case ARRAY:
        setField(statement, column, schema, index, object);
        break;
    case BOOLEAN:
        statement.setBoolean(index, (Boolean) object);
        break;
    case BYTES:
        setBytes(statement, column, index, ((ByteBuffer) object).array());
        break;
    case DOUBLE:
        statement.setDouble(index, (Double) object);
        break;
    case ENUM:
        statement.setString(index, ((Enum<?>) object).name());
        break;
    case FIXED:
        setBytes(statement, column, index, ((GenericFixed) object).bytes());
        break;
    case FLOAT:
        statement.setFloat(index, (Float) object);
        break;
    case INT:
        statement.setInt(index, (Integer) object);
        break;
    case LONG:
        statement.setLong(index, (Long) object);
        break;
    case NULL:
        break;
    case RECORD:
        setField(statement, column, schema, index, object);
        break;
    case STRING:
        statement.setString(index, ((Utf8) object).toString());
        break;
    case UNION:
        throw new IOException("Union is not supported yet");
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.jdbc.JdbcScimUserProvisioning.java

@Override
public ScimUser create(final ScimUser user) {
    if (!hasText(user.getOrigin())) {
        user.setOrigin(OriginKeys.UAA);/*from   w  w  w  . j a va2 s  .  c om*/
    }
    validate(user);
    logger.debug("Creating new user: " + user.getUserName());

    final String id = UUID.randomUUID().toString();
    final String identityZoneId = IdentityZoneHolder.get().getId();
    final String origin = user.getOrigin();

    try {
        jdbcTemplate.update(CREATE_USER_SQL, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                Timestamp t = new Timestamp(new Date().getTime());
                ps.setString(1, id);
                ps.setInt(2, user.getVersion());
                ps.setTimestamp(3, t);
                ps.setTimestamp(4, t);
                ps.setString(5, user.getUserName());
                ps.setString(6, user.getPrimaryEmail());
                if (user.getName() == null) {
                    ps.setString(7, null);
                    ps.setString(8, null);
                } else {
                    ps.setString(7, user.getName().getGivenName());
                    ps.setString(8, user.getName().getFamilyName());
                }
                ps.setBoolean(9, user.isActive());
                String phoneNumber = extractPhoneNumber(user);
                ps.setString(10, phoneNumber);
                ps.setBoolean(11, user.isVerified());
                ps.setString(12, origin);
                ps.setString(13, hasText(user.getExternalId()) ? user.getExternalId() : null);
                ps.setString(14, identityZoneId);
                ps.setString(15, user.getSalt());

                ps.setTimestamp(16, getPasswordLastModifiedTimestamp(t));
                ps.setNull(17, Types.BIGINT);
                ps.setNull(18, Types.BIGINT);
                ps.setString(19, user.getPassword());
            }

        });
    } catch (DuplicateKeyException e) {
        ScimUser existingUser = query("userName eq \"" + user.getUserName() + "\" and origin eq \""
                + (hasText(user.getOrigin()) ? user.getOrigin() : OriginKeys.UAA) + "\"").get(0);
        Map<String, Object> userDetails = new HashMap<>();
        userDetails.put("active", existingUser.isActive());
        userDetails.put("verified", existingUser.isVerified());
        userDetails.put("user_id", existingUser.getId());
        throw new ScimResourceAlreadyExistsException("Username already in use: " + existingUser.getUserName(),
                userDetails);
    }
    return retrieve(id);
}

From source file:chh.utils.db.source.common.JdbcClient.java

private void setPreparedStatementParams(PreparedStatement preparedStatement, List<Column> columnList)
        throws SQLException {
    int index = 1;
    for (Column column : columnList) {
        Class columnJavaType = Util.getJavaType(column.getSqlType());
        if (column.getVal() == null) {
            preparedStatement.setNull(index, column.getSqlType());
        } else if (columnJavaType.equals(String.class)) {
            preparedStatement.setString(index, (String) column.getVal());
        } else if (columnJavaType.equals(Integer.class)) {
            preparedStatement.setInt(index, (Integer) column.getVal());
        } else if (columnJavaType.equals(Double.class)) {
            preparedStatement.setDouble(index, (Double) column.getVal());
        } else if (columnJavaType.equals(Float.class)) {
            preparedStatement.setFloat(index, (Float) column.getVal());
        } else if (columnJavaType.equals(Short.class)) {
            preparedStatement.setShort(index, (Short) column.getVal());
        } else if (columnJavaType.equals(Boolean.class)) {
            preparedStatement.setBoolean(index, (Boolean) column.getVal());
        } else if (columnJavaType.equals(byte[].class)) {
            preparedStatement.setBytes(index, (byte[]) column.getVal());
        } else if (columnJavaType.equals(Long.class)) {
            preparedStatement.setLong(index, (Long) column.getVal());
        } else if (columnJavaType.equals(Date.class)) {
            preparedStatement.setDate(index, (Date) column.getVal());
        } else if (columnJavaType.equals(Time.class)) {
            preparedStatement.setTime(index, (Time) column.getVal());
        } else if (columnJavaType.equals(Timestamp.class)) {
            preparedStatement.setTimestamp(index, (Timestamp) column.getVal());
        } else {/*from w  w  w  .  ja v  a  2  s  . com*/
            throw new RuntimeException(
                    "Unknown type of value " + column.getVal() + " for column " + column.getColumnName());
        }
        ++index;
    }
}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

private Map<XidImpl, TransactionArchive> loadTransactionSet(Connection connection) {
    Map<XidImpl, TransactionArchive> metaMap = new HashMap<XidImpl, TransactionArchive>();
    PreparedStatement stmt = null;
    ResultSet rs = null;/*ww w .  ja  v  a  2  s .  c om*/
    try {
        StringBuilder ber = new StringBuilder();
        ber.append("select global_tx_id, status, status_trace");
        ber.append(", coordinator, created_time ");
        ber.append("from tcc_transaction ");
        ber.append("where application = ? and endpoint = ? and deleted = ?");
        stmt = connection.prepareStatement(ber.toString());
        stmt.setString(1, this.instanceKey.getApplication());
        stmt.setString(2, this.instanceKey.getEndpoint());
        stmt.setBoolean(3, false);
        rs = stmt.executeQuery();
        while (rs.next()) {
            String globalTransactionId = rs.getString("global_tx_id");
            int state = rs.getInt("status");
            int trace = rs.getInt("status_trace");
            boolean coordinator = rs.getBoolean("coordinator");
            Timestamp createdTime = rs.getTimestamp("created_time");

            TransactionContext context = new TransactionContext();

            TerminalKey terminalKey = new TerminalKey();

            terminalKey.setApplication(this.instanceKey.getApplication());
            terminalKey.setEndpoint(this.instanceKey.getEndpoint());
            context.setTerminalKey(terminalKey);

            context.setRecovery(true);
            context.setCompensable(true);
            context.setCoordinator(coordinator);
            byte[] globalBytes = ByteUtils.stringToByteArray(globalTransactionId);
            XidImpl globalXid = this.xidFactory.createGlobalXid(globalBytes);
            // context.setGlobalXid(globalXid);
            context.setCreationXid(globalXid);
            context.setCurrentXid(globalXid);

            context.setCreatedTime(createdTime.getTime());

            TransactionStatus status = new TransactionStatus(state, trace);
            TransactionArchive meta = new TransactionArchive();
            meta.setTransactionStatus(status);
            meta.setTransactionContext(context);

            metaMap.put(globalXid, meta);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        closeResultSet(rs);
        closeStatement(stmt);
    }

    return metaMap;
}

From source file:com.flexive.ejb.beans.LanguageBean.java

/**
 * {@inheritDoc}//  w  w  w . j av  a 2  s . c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setAvailable(List<FxLanguage> available, boolean ignoreUsage) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.GlobalSupervisor);
    Connection con = null;
    PreparedStatement ps = null;
    if (available == null || available.size() == 0)
        throw new FxInvalidParameterException("available", "ex.language.noAvailable");
    try {
        con = Database.getDbConnection();
        if (!ignoreUsage) {
            List<FxLanguage> orgLang = loadAvailable(true);
            boolean found;
            for (FxLanguage org : orgLang) {
                found = false;
                for (FxLanguage tmp : available) {
                    if (tmp.getId() == org.getId()) {
                        found = true;
                        break;
                    }
                }
                if (!found && hasUsages(con, org))
                    throw new FxInvalidParameterException("available", "ex.language.removeUsed",
                            org.getLabel());
            }
        }
        ps = con.prepareStatement("UPDATE " + TBL_LANG + " SET INUSE=?, DISPPOS=?");
        ps.setBoolean(1, false);
        ps.setNull(2, java.sql.Types.INTEGER);
        ps.executeUpdate();
        ps.close();
        int pos = 0;
        ps = con.prepareStatement("UPDATE " + TBL_LANG + " SET INUSE=?, DISPPOS=? WHERE LANG_CODE=?");
        ps.setBoolean(1, true);
        for (FxLanguage lang : available) {
            ps.setInt(2, pos++);
            ps.setLong(3, lang.getId());
            ps.addBatch();
        }
        ps.executeBatch();
        StructureLoader.updateLanguages(FxContext.get().getDivisionId(), loadAll(true, true));
    } catch (FxCacheException e) {
        LOG.error(e, e);
    } catch (SQLException e) {
        throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(LanguageBean.class, con, ps);
    }
}

From source file:lcn.module.batch.core.item.database.support.MethodMapItemPreparedStatementSetter.java

/**
 * params ? ? sqlType PreparedStatement? ??
 *//*from   ww  w.  ja v  a 2s.  co  m*/
public void setValues(T item, PreparedStatement ps, String[] params, String[] sqlTypes,
        Map<String, Method> methodMap) throws SQLException {

    ReflectionSupport<T> reflector = new ReflectionSupport<T>();

    for (int i = 0; i < params.length; i++) {
        try {

            if (sqlTypes[i].equals("String")) {
                ps.setString(i + 1, (String) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("int")) {
                ps.setInt(i + 1, (Integer) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("double")) {
                ps.setDouble(i + 1, (Double) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Date")) {
                ps.setDate(i + 1, (Date) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte")) {
                ps.setByte(i + 1, (Byte) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("short")) {
                ps.setShort(i + 1, (Short) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("boolean")) {
                ps.setBoolean(i + 1, (Boolean) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("long")) {
                ps.setLong(i + 1, (Long) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Float")) {
                ps.setFloat(i + 1, (Float) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("BigDecimal")) {
                ps.setBigDecimal(i + 1, (BigDecimal) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte[]")) {
                ps.setBytes(i + 1, (byte[]) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else {
                throw new SQLException();
            }
        } catch (IllegalArgumentException e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }
}