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.sleuthkit.autopsy.imageanalyzer.datamodel.DrawableDB.java

private void insertOrUpdateFile(DrawableFile<?> f, DrawableTransaction tr, PreparedStatement stmt) {

    //TODO:      implement batch version -jm
    if (tr.isClosed()) {
        throw new IllegalArgumentException("can't update database with closed transaction");
    }// w w  w .ja v a 2 s. c  om
    dbWriteLock();
    try {

        // "INSERT OR IGNORE/ INTO drawable_files (path, name, created_time, modified_time, make, model, analyzed)"
        stmt.setLong(1, f.getId());
        stmt.setString(2, f.getDrawablePath());
        stmt.setString(3, f.getName());
        stmt.setLong(4, f.getCrtime());
        stmt.setLong(5, f.getMtime());
        stmt.setString(6, f.getMake());
        stmt.setString(7, f.getModel());
        stmt.setBoolean(8, f.isAnalyzed());
        stmt.executeUpdate();

        final Collection<String> hashSetNames = DrawableAttribute.HASHSET.getValue(f);

        if (hashSetNames.isEmpty() == false) {
            for (String name : hashSetNames) {

                // "insert or ignore into hash_sets (hash_set_name)  values (?)"
                insertHashSetStmt.setString(1, name);
                insertHashSetStmt.executeUpdate();

                //TODO: use nested select to get hash_set_id rather than seperate statement/query
                //"select hash_set_id from hash_sets where hash_set_name = ?"
                selectHashSetStmt.setString(1, name);
                try (ResultSet rs = selectHashSetStmt.executeQuery()) {
                    while (rs.next()) {
                        int hashsetID = rs.getInt("hash_set_id");
                        //"insert or ignore into hash_set_hits (hash_set_id, obj_id) values (?,?)";
                        insertHashHitStmt.setInt(1, hashsetID);
                        insertHashHitStmt.setLong(2, f.getId());
                        insertHashHitStmt.executeUpdate();
                        break;
                    }
                }
            }
        }

        //and update all groups this file is in
        for (DrawableAttribute<?> attr : DrawableAttribute.getGroupableAttrs()) {
            Collection<? extends Comparable<?>> vals = attr.getValue(f);
            for (Object val : vals) {
                insertGroup(val.toString(), attr);
            }
        }

        tr.addUpdatedFile(f.getId());

    } catch (SQLException ex) {
        LOGGER.log(Level.SEVERE, "failed to insert/update file" + f.getName(), ex);
    } finally {
        dbWriteUnlock();
    }
}

From source file:org.ecoinformatics.seek.dataquery.DBTablesGenerator.java

private synchronized PreparedStatement setupPreparedStatmentParameter(int index, PreparedStatement pStatement,
        String data, String javaDataType)
        throws SQLException, UnresolvableTypeException, IllegalArgumentException {
    if (pStatement == null) {
        return pStatement;
    }//from  ww w .  j  a v a  2 s  . c o  m

    // get rid of white space
    if (data != null) {
        data = data.trim();
    }

    // set default type as string
    if (javaDataType == null) {
        pStatement.setString(index, data);
    } else {

        if (javaDataType.equals(STRING)) {
            pStatement.setString(index, data);
        } else if (javaDataType.equals(INTEGER)) {
            pStatement.setInt(index, (new Integer(data)).intValue());
        } else if (javaDataType.equals(DOUBLE)) {
            pStatement.setDouble(index, (new Double(data)).doubleValue());
        } else if (javaDataType.equals(FLOAT)) {
            pStatement.setFloat(index, (new Float(data)).floatValue());
        } else if (javaDataType.equals(BOOLEAN)) {
            pStatement.setBoolean(index, (new Boolean(data)).booleanValue());
        } else if (javaDataType.equals(LONG)) {
            pStatement.setLong(index, (new Long(data)).longValue());
        } else if (javaDataType.equals(DATETIME)) {
            pStatement.setTimestamp(index, Timestamp.valueOf(data));
        } else {
            throw new UnresolvableTypeException("This java type " + javaDataType + " has NOT implement in "
                    + "DBTablesGenerator.setupPreparedStatmentParameter method");
        }
    }
    return pStatement;
}

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

/**
 * {@inheritDoc}/*w  ww .j  a  va 2s. co m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assign(long aclId, long groupId, boolean mayRead, boolean mayEdit, boolean mayRelate,
        boolean mayRemove, boolean mayExport, boolean mayCreate) throws FxApplicationException {
    UserTicket ticket = FxContext.getUserTicket();
    // Delete rather than create?
    if (!mayRead && !mayRelate && !mayExport && !mayEdit && !mayRemove && !mayCreate) {
        try {
            unassign(aclId, groupId);
        } catch (FxNotFoundException e) {
            // ignore missing assignments
        } catch (FxRemoveException exc) {
            throw new FxCreateException(exc.getMessage(), exc);
        }
        return;
    }

    // Permission & exists check
    checkPermissions(ticket, groupId, aclId, true);

    Connection con = null;
    PreparedStatement stmt = null;
    String curSql;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        // Delete any old assignments
        curSql = "DELETE FROM " + TBL_ACLS_ASSIGNMENT + " WHERE USERGROUP=" + groupId + " AND ACL=" + aclId;
        stmt = con.prepareStatement(curSql);
        int ucount = stmt.executeUpdate();
        stmt.close();
        if (LOG.isDebugEnabled())
            LOG.debug("Deleted assignments group[" + groupId + "]-acl[" + aclId + "]:" + ucount);

        curSql = "INSERT INTO " + TBL_ACLS_ASSIGNMENT +
        //1         2   3     4     5       6       7       8     9          10         11          12
                "(USERGROUP,ACL,PREAD,PEDIT,PREMOVE,PCREATE,PEXPORT,PREL,CREATED_AT,CREATED_BY,MODIFIED_AT,MODIFIED_BY)"
                + " VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?)";

        final long NOW = System.currentTimeMillis();
        stmt = con.prepareStatement(curSql);
        stmt.setLong(1, groupId);
        stmt.setLong(2, aclId);
        stmt.setBoolean(3, mayRead);
        stmt.setBoolean(4, mayEdit);
        stmt.setBoolean(5, mayRemove);
        stmt.setBoolean(6, mayCreate);
        stmt.setBoolean(7, mayExport);
        stmt.setBoolean(8, mayRelate);
        stmt.setLong(9, NOW);
        stmt.setLong(10, ticket.getUserId());
        stmt.setLong(11, NOW);
        stmt.setLong(12, ticket.getUserId());

        stmt.executeUpdate();

        // Update active UserTickets
        UserTicketStore.flagDirtyHavingGroupId(groupId);

        final ACL acl = CacheAdmin.getEnvironment().getACL(aclId);
        final ACLAssignment as = new ACLAssignment(aclId, groupId, mayRead, mayEdit, mayRelate, mayRemove,
                mayExport, mayCreate, acl.getCategory(), acl.getLifeCycleInfo());
        EJBLookup.getHistoryTrackerEngine().trackData(ConversionEngine.getXStream().toXML(as),
                "history.acl.assign", acl.getName());
    } catch (Exception exc) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, exc, "ex.aclAssignment.createFailed");
    } finally {
        Database.closeObjects(ACLEngineBean.class, con, stmt);
    }

}

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

/**
 * {@inheritDoc}//from   w  w  w . j a va 2  s.com
 */
@Override
public FxTreeNodeInfo getTreeNodeInfo(Connection con, FxTreeMode mode, long nodeId)
        throws FxApplicationException {
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement(mode == FxTreeMode.Live ? TREE_LIVE_MAXRIGHT : TREE_EDIT_MAXRIGHT);
        ps.setLong(1, nodeId);
        ResultSet rs = ps.executeQuery();
        if (rs == null || !rs.next())
            throw new FxNotFoundException("ex.tree.node.notFound", nodeId, mode);
        BigInteger maxRight = getNodeBounds(rs, 1);
        ps.close();
        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);
        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 FxTreeNodeInfoSpreaded(getNodeBounds(rs, 1), getNodeBounds(rs, 2), getNodeBounds(rs, 5),
                getNodeBounds(rs, 6), maxRight, 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) {
        final DBStorage db = StorageManager.getStorageImpl();
        if (db.isDeadlock(e) || db.isQueryTimeout(e)) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Deadlock detected while reading node info, waiting 100ms and retrying...");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                // ignore
            }
            // try again
            return getTreeNodeInfo(con, mode, nodeId);
        }
        throw new FxTreeException(e, "ex.tree.nodeInfo.sqlError", nodeId, e.getMessage());
    } finally {
        Database.closeObjects(GenericTreeStorageSpreaded.class, null, ps);
    }
}

From source file:edu.umd.cs.marmoset.modelClasses.Project.java

private int putValues(PreparedStatement stmt, int index) throws SQLException {
    stmt.setInt(index++, Course.asPK(getCoursePK()));
    stmt.setInt(index++, getTestSetupPK());
    stmt.setInt(index++, getDiffAgainst());
    stmt.setString(index++, getProjectNumber());
    stmt.setTimestamp(index++, getOntime());
    stmt.setTimestamp(index++, getLate());
    stmt.setString(index++, getTitle());
    stmt.setString(index++, getUrl());/*from w  w  w.  ja v  a2 s .c  o m*/
    stmt.setString(index++, getDescription());
    stmt.setInt(index++, getReleaseTokens());
    stmt.setInt(index++, getRegenerationTime());
    stmt.setBoolean(index++, isTested());
    stmt.setBoolean(index++, isPair());
    stmt.setBoolean(index++, getVisibleToStudents());
    stmt.setString(index++, getPostDeadlineOutcomeVisibility());
    stmt.setString(index++, getKindOfLatePenalty());
    stmt.setDouble(index++, getLateMultiplier());
    stmt.setInt(index++, getLateConstant());
    stmt.setInt(index++, getCanonicalStudentRegistrationPK());
    stmt.setString(index++, getBestSubmissionPolicy());
    stmt.setString(index++, getReleasePolicy());
    stmt.setString(index++, getStackTracePolicy());
    // Using -1 to represent infinity in the database
    if (getNumReleaseTestsRevealed() == Integer.MAX_VALUE)
        stmt.setInt(index++, -1);
    else
        stmt.setInt(index++, getNumReleaseTestsRevealed());
    SqlUtilities.setInteger(stmt, index++, getArchivePK());
    stmt.setString(index++, browserEditing.name().toLowerCase());
    return index;
}

From source file:org.brucalipto.sqlutil.SQLManager.java

protected int executeSimpleQuery(final String preparedStatement, final SQLParameter[] params) {
    final SQLParameter[] parameters;
    if (params == null) {
        parameters = new SQLParameter[0];
        log.debug("Going to execute a query without parameters.");
    } else {/*  w w w  .ja v a  2  s . c  o  m*/
        parameters = (SQLParameter[]) params.clone();
    }
    Connection dbConn = null;
    PreparedStatement pstmt = null;
    try {
        if (this.dataSource != null) {
            dbConn = this.dataSource.getConnection();
        } else {
            dbConn = this.connection;
        }
        pstmt = dbConn.prepareStatement(preparedStatement);
        for (int i = 0; i < parameters.length; i++) {
            final SQLParameter param = parameters[i];
            log.debug((i + 1) + ") Going to add parameter " + param);
            final int sqlType = param.getSqlType();
            final Object paramValue = param.getValue();
            if (paramValue == null) {
                pstmt.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                pstmt.setString(i + 1, (String) paramValue);
                break;
            case Types.INTEGER:
                if (paramValue instanceof Integer) {
                    pstmt.setInt(i + 1, ((Integer) paramValue).intValue());
                } else if (paramValue instanceof Long) {
                    pstmt.setLong(i + 1, ((Long) paramValue).longValue());
                }
                break;
            case Types.DATE:
                pstmt.setDate(i + 1, (Date) paramValue);
                break;
            case Types.BOOLEAN:
                pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue());
                break;
            case Types.CHAR:
                pstmt.setString(i + 1, ((Character) paramValue).toString());
                break;
            case Types.DOUBLE:
                pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue());
                break;
            case Types.FLOAT:
                pstmt.setFloat(i + 1, ((Float) paramValue).floatValue());
                break;
            case Types.TIMESTAMP:
                pstmt.setTimestamp(i + 1, (Timestamp) paramValue);
                break;
            default:
                pstmt.setObject(i + 1, paramValue);
                break;
            }
        }

        int result = pstmt.executeUpdate();
        log.debug("Prepared statement '" + preparedStatement + "' correctly executed (" + result + ")");
        return result;
    } catch (SQLException e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } catch (Exception e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } finally {
        closeResources(pstmt, dbConn);
    }

    return -1;
}

From source file:com.enonic.vertical.engine.handlers.SectionHandler.java

private void addSectionContent(User user, int sectionKey, int contentKey, int order, boolean approved)
        throws VerticalCreateException, VerticalSecurityException {

    SecurityHandler securyHandler = getSecurityHandler();
    if (!securyHandler.validateContentAddToSection(user, sectionKey)) {
        String message = "User is not allowed to add content to this section: %0";
        VerticalEngineLogger.errorSecurity(this.getClass(), 0, message, sectionKey, null);
    }/*from  w ww  .  j ava 2s .  c om*/

    // First, check for contenttype filters
    TIntArrayList contentTypes = new TIntArrayList();
    contentTypes.add(getContentTypesForSection(sectionKey));
    if (contentTypes.size() > 0) {
        int contentTypeKey = getContentHandler().getContentTypeKey(contentKey);
        if (!contentTypes.contains(contentTypeKey)) {
            String message = "Section does not allow this content type: %0";
            VerticalEngineLogger.errorCreate(this.getClass(), 0, message, contentTypeKey, null);
        }
    }
    Connection con = null;
    PreparedStatement preparedStmt = null;

    try {
        con = getConnection();
        StringBuffer sql = XDG.generateInsertSQL(db.tSectionContent2);

        preparedStmt = con.prepareStatement(sql.toString());
        int scoPrimaryKey = getCommonHandler().getNextKey(db.tSectionContent2.getName());
        preparedStmt.setInt(1, scoPrimaryKey);
        preparedStmt.setInt(2, contentKey);
        preparedStmt.setInt(3, sectionKey);
        preparedStmt.setInt(4, order);
        preparedStmt.setBoolean(5, approved);

        int result = preparedStmt.executeUpdate();
        if (result == 0) {
            String message = "Failed to add content to section.";
            VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
        }
    } catch (SQLException sqle) {
        String message = "Failed to add content to section: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 1, message, sqle);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

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

@Override
public void enlistService(TransactionContext transactionContext, CompensableArchive holder) {
    Connection connection = null;
    PreparedStatement stmt = null;
    try {//from   w ww.j  a  v a2  s  . c  o m
        connection = this.getConnection();

        StringBuilder ber = new StringBuilder();
        ber.append("insert into tcc_compensable(");
        ber.append("application, endpoint, global_tx_id, branch_qualifier");
        ber.append(", coordinator, bean_name) values (?, ?, ?, ?, ?, ?)");
        stmt = connection.prepareStatement(ber.toString());

        Compensable<Serializable> service = holder.service;
        CompensableInfo servInfo = this.compensableMarshaller.marshallCompensable(service);
        XidImpl internalXid = holder.branchXid;
        TerminalKey terminalKey = transactionContext.getTerminalKey();

        stmt.setString(1, terminalKey.getApplication());
        stmt.setString(2, terminalKey.getEndpoint());
        stmt.setString(3, ByteUtils.byteArrayToString(internalXid.getGlobalTransactionId()));
        if (transactionContext.isCoordinator()) {
            stmt.setString(4, TransactionLogger.NULL);
        } else {
            stmt.setString(4, ByteUtils.byteArrayToString(internalXid.getBranchQualifier()));
        }
        stmt.setBoolean(5, holder.launchSvc);
        stmt.setString(6, String.valueOf(servInfo.getIdentifier()));

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

From source file:org.brucalipto.sqlutil.SQLManager.java

/**
 * Method useful for SQL SELECT//from w  ww . j a  v  a 2 s .c  o m
 * @param preparedStatement The prepared statement to execute
 * @param params List of {@link SQLParameter} to use to complete the prepared statement
 * @param outputSQLType A java.sql.Types type of return value
 * @return The {@link SPParameter} containing the returned value
 */
public SQLParameter simpleSelect(final String preparedStatement, SQLParameter[] params,
        final int outputSQLType) {
    final SQLParameter[] parameters;
    if (params == null) {
        parameters = new SQLParameter[0];
        log.debug("Going to execute a query without parameters.");
    } else {
        parameters = (SQLParameter[]) params.clone();
    }
    Connection dbConn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        if (this.dataSource != null) {
            dbConn = this.dataSource.getConnection();
        } else {
            dbConn = this.connection;
        }
        pstmt = dbConn.prepareStatement(preparedStatement);
        for (int i = 0; i < parameters.length; i++) {
            final SQLParameter param = parameters[i];
            log.debug((i + 1) + ") Going to add parameter " + param);
            final int sqlType = param.getSqlType();
            final Object paramValue = param.getValue();
            if (paramValue == null) {
                pstmt.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                pstmt.setString(i + 1, (String) paramValue);
                break;
            case Types.INTEGER:
                if (paramValue instanceof Integer) {
                    pstmt.setInt(i + 1, ((Integer) paramValue).intValue());
                } else if (paramValue instanceof Long) {
                    pstmt.setLong(i + 1, ((Long) paramValue).longValue());
                }
                break;
            case Types.DATE:
                pstmt.setDate(i + 1, (Date) paramValue);
                break;
            case Types.BOOLEAN:
                pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue());
                break;
            case Types.CHAR:
                pstmt.setString(i + 1, ((Character) paramValue).toString());
                break;
            case Types.DOUBLE:
                pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue());
                break;
            case Types.FLOAT:
                pstmt.setFloat(i + 1, ((Float) paramValue).floatValue());
                break;
            case Types.TIMESTAMP:
                pstmt.setTimestamp(i + 1, (Timestamp) paramValue);
                break;
            default:
                pstmt.setObject(i + 1, paramValue);
                break;
            }
        }

        rs = pstmt.executeQuery();
        log.debug("Prepared statement '" + preparedStatement + "' succesfully executed!");
        while (rs.next()) {
            return new SQLParameter(outputSQLType, (Serializable) rs.getObject(1));
        }
        log.info("Prepared statement '" + preparedStatement + "' returned '0' rows");
    } catch (SQLException e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } catch (Exception e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } finally {
        closeResources(rs, pstmt, dbConn);
    }

    return new SQLParameter(outputSQLType, null);
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param preparedState/*from w  w w. j a  v  a2 s . c  om*/
 * @param param
 * @throws SQLException
 */
private void setParam(PreparedStatement preparedState, int index, StateParam param) throws SQLException {
    boolean isNull = (null == param.getValue());

    Class<?> clazz = Object.class;
    try {
        clazz = Class.forName(param.getClassName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Rep rep = Rep.of(clazz);

    switch (rep) {
    case PRIMITIVE_CHAR:
    case CHARACTER:
    case STRING:
        preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
        break;
    case PRIMITIVE_INT:
    case INTEGER:
        preparedState.setInt(index, isNull ? null : Integer.valueOf(param.getValue()));
        break;
    case PRIMITIVE_SHORT:
    case SHORT:
        preparedState.setShort(index, isNull ? null : Short.valueOf(param.getValue()));
        break;
    case PRIMITIVE_LONG:
    case LONG:
        preparedState.setLong(index, isNull ? null : Long.valueOf(param.getValue()));
        break;
    case PRIMITIVE_FLOAT:
    case FLOAT:
        preparedState.setFloat(index, isNull ? null : Float.valueOf(param.getValue()));
        break;
    case PRIMITIVE_DOUBLE:
    case DOUBLE:
        preparedState.setDouble(index, isNull ? null : Double.valueOf(param.getValue()));
        break;
    case PRIMITIVE_BOOLEAN:
    case BOOLEAN:
        preparedState.setBoolean(index, isNull ? null : Boolean.parseBoolean(param.getValue()));
        break;
    case PRIMITIVE_BYTE:
    case BYTE:
        preparedState.setByte(index, isNull ? null : Byte.valueOf(param.getValue()));
        break;
    case JAVA_UTIL_DATE:
    case JAVA_SQL_DATE:
        preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIME:
        preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIMESTAMP:
        preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
        break;
    default:
        preparedState.setObject(index, isNull ? null : param.getValue());
    }
}