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:ece356.UserDBAO.java

public static FriendShipStatus addFriend(String friendA, String friendB)
        throws ClassNotFoundException, SQLException, NamingException {
    Connection con = null;//from   ww w  . j  av a2  s . com
    PreparedStatement pstmt = null;
    try {
        con = getConnection();
        // First check if sender has already sent a request to receiver in the past
        // If he has, then check if it's accepted
        // If it is accepted, then return ALREADY_FRIENDS
        // If it is not accepted, then return WAITING_FOR_ACCEPT
        // If he hasn't then check if the receiver has sent a request to sender in the past
        // If he hasn't, then make an INSERT and return REQUEST_SENT
        // If he has, then check if it's accepted
        // If it's not accepted, then UPDATE and make isAccepted = true and return FRIENDSHIP_ESTABLISHED                            
        // If it is accepted, then return ALREADY_FRIENDS                        

        // Find if this request is already there
        String query = "SELECT * FROM friend where sent_username = ? AND recieved_username = ?";
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, friendA);
        pstmt.setString(2, friendB);

        ResultSet resultSet;
        resultSet = pstmt.executeQuery();
        resultSet.next();

        if (resultSet.first()) {
            System.out.println("RESULT SET: " + resultSet.getString("sent_username") + " "
                    + resultSet.getString("recieved_username"));
            boolean isAccepted = resultSet.getBoolean("isAccepted");
            if (isAccepted) {
                return FriendShipStatus.ALREADY_FRIENDS;
            } else {
                return FriendShipStatus.WAITING_FOR_ACCEPT;
            }
        } else {
            pstmt = con.prepareStatement(query);
            pstmt.setString(1, friendB);
            pstmt.setString(2, friendA);
            resultSet = pstmt.executeQuery();
            resultSet.next();
            if (resultSet.first()) {
                System.out.println("RESULT SET: " + resultSet.getString("sent_username") + " "
                        + resultSet.getString("recieved_username"));
                boolean isAccepted = resultSet.getBoolean("isAccepted");
                if (isAccepted) {
                    return FriendShipStatus.ALREADY_FRIENDS;
                } else {
                    String update = "UPDATE friend SET isAccepted = ? where sent_username = ? AND recieved_username = ?;";
                    pstmt = con.prepareStatement(update);
                    pstmt.setBoolean(1, true);
                    pstmt.setString(2, friendB);
                    pstmt.setString(3, friendA);
                    pstmt.executeUpdate();
                    return FriendShipStatus.FRIENDSHIP_ESTABLISHED;
                }
            } else {
                pstmt = con.prepareStatement(
                        "INSERT INTO friend (sent_username, recieved_username) VALUES (?, ?);");
                pstmt.setString(1, friendA);
                pstmt.setString(2, friendB);
                pstmt.executeUpdate();
                return FriendShipStatus.REQUEST_SENT;
            }
        }
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (con != null) {
            con.close();
        }
    }
}

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

/**
 * {@inheritDoc}/*from  ww  w.  ja v a  2 s  .  co m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateScriptInfo(FxScriptInfoEdit script) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    try {
        String code = "";
        if (script.getCode() != null)
            code = script.getCode();
        // Obtain a database connection
        con = Database.getDbConnection();
        //                                          1       2       3       4    5         6              7
        sql = "UPDATE " + TBL_SCRIPTS + " SET SNAME=?,SDESC=?,SDATA=?,STYPE=?,ACTIVE=?,IS_CACHED=? WHERE ID=?";
        ps = con.prepareStatement(sql);
        ps.setString(1, script.getName());
        ps.setString(2, script.getDescription());
        StorageManager.setBigString(ps, 3, code);
        ps.setLong(4, script.getEvent().getId());
        ps.setBoolean(5, script.isActive());
        ps.setBoolean(6, script.isCached());
        ps.setLong(7, script.getId());
        ps.executeUpdate();
        // remove script from cache if necessary
        if (FxSharedUtils.isGroovyScript(script.getName()) && !script.isCached())
            LocalScriptingCache.groovyScriptCache.remove(script.getId());
        success = true;
    } catch (SQLException exc) {
        throw new FxUpdateException(LOG, exc, "ex.scripting.update.failed", script.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
}

From source file:com.flexive.ejb.beans.structure.TypeEngineBean.java

private void storeTypeOptions(Connection con, String table, String primaryColumn, long id, // Long assignmentId,
        List<FxStructureOption> options, boolean update) throws SQLException, FxInvalidParameterException {
    PreparedStatement ps = null;
    try {/*from   w ww. ja  v a 2  s  . c  o  m*/
        if (update) {
            ps = con.prepareStatement("DELETE FROM " + table + " WHERE " + primaryColumn + "=?");
            ps.setLong(1, id);
            ps.executeUpdate();
            ps.close();
        }

        if (options == null || options.size() == 0)
            return;
        //                                                        1                 2      3           4        5
        ps = con.prepareStatement("INSERT INTO " + table + " (" + primaryColumn
                + ",OPTKEY,MAYOVERRIDE,ISINHERITED,OPTVALUE)VALUES(?,?,?,?,?)");
        for (FxStructureOption option : options) {
            ps.setLong(1, id);
            if (StringUtils.isEmpty(option.getKey()))
                throw new FxInvalidParameterException("key", "ex.structure.option.key.empty",
                        option.getValue());
            ps.setString(2, option.getKey());
            ps.setBoolean(3, option.isOverridable());
            ps.setBoolean(4, option.getIsInherited());
            ps.setString(5, option.getValue());
            ps.addBatch();
        }
        ps.executeBatch();
    } finally {
        if (ps != null)
            ps.close();
    }
}

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

/**
 * Create a harvest definition in Database. The harvest definition object
 * should not have its ID set unless we are in the middle of migrating.
 *
 * @param harvestDefinition//from  w  ww.  jav a 2  s  .c om
 *            A new harvest definition to store in the database.
 * @return The harvestId for the just created harvest definition.
 * @see HarvestDefinitionDAO#create(HarvestDefinition)
 */
@Override
public synchronized Long create(HarvestDefinition harvestDefinition) {
    Connection connection = HarvestDBConnection.get();
    PreparedStatement s = null;
    try {
        Long id = harvestDefinition.getOid();
        if (id == null) {
            id = generateNextID(connection);
        }

        connection.setAutoCommit(false);
        s = connection.prepareStatement(
                "INSERT INTO harvestdefinitions " + "( harvest_id, name, comments, numevents, submitted,"
                        + "  isactive, edition, audience ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?,? )");
        s.setLong(1, id);
        DBUtils.setName(s, 2, harvestDefinition, Constants.MAX_NAME_SIZE);
        DBUtils.setComments(s, 3, harvestDefinition, Constants.MAX_COMMENT_SIZE);
        s.setLong(4, harvestDefinition.getNumEvents());
        Date submissiondate = new Date();
        // Don't set on object, as we may yet rollback
        s.setTimestamp(5, new Timestamp(submissiondate.getTime()));
        s.setBoolean(6, harvestDefinition.getActive());
        final int edition = 1;
        s.setLong(7, edition);
        s.setString(8, harvestDefinition.getAudience());
        s.executeUpdate();
        s.close();
        if (harvestDefinition instanceof FullHarvest) {
            FullHarvest fh = (FullHarvest) harvestDefinition;
            s = connection.prepareStatement("INSERT INTO fullharvests " + "( harvest_id, maxobjects, maxbytes,"
                    + " maxjobrunningtime, previoushd, isindexready)" + "VALUES ( ?, ?, ?, ?, ?, ? )");
            s.setLong(1, id);
            s.setLong(2, fh.getMaxCountObjects());
            s.setLong(3, fh.getMaxBytes());
            s.setLong(4, fh.getMaxJobRunningTime());
            if (fh.getPreviousHarvestDefinition() != null) {
                s.setLong(5, fh.getPreviousHarvestDefinition().getOid());
            } else {
                s.setNull(5, Types.BIGINT);
            }
            s.setBoolean(6, fh.getIndexReady());
            s.executeUpdate();
        } else if (harvestDefinition instanceof PartialHarvest) {
            PartialHarvest ph = (PartialHarvest) harvestDefinition;
            // Get schedule id
            long scheduleId = DBUtils.selectLongValue(connection,
                    "SELECT schedule_id FROM schedules WHERE name = ?", ph.getSchedule().getName());
            s = connection.prepareStatement("INSERT INTO partialharvests "
                    + "( harvest_id, schedule_id, nextdate ) " + "VALUES ( ?, ?, ? )");
            s.setLong(1, id);
            s.setLong(2, scheduleId);
            DBUtils.setDateMaybeNull(s, 3, ph.getNextDate());
            s.executeUpdate();
            createHarvestConfigsEntries(connection, ph, id);
        } else {
            String message = "Harvest definition " + harvestDefinition + " is of unknown class "
                    + harvestDefinition.getClass();
            log.warn(message);
            throw new ArgumentNotValid(message);
        }
        connection.commit();

        // Now that we have committed, set new data on object.
        harvestDefinition.setSubmissionDate(submissiondate);
        harvestDefinition.setEdition(edition);
        harvestDefinition.setOid(id);

        // saving after receiving id
        saveExtendedFieldValues(connection, harvestDefinition);

        return id;
    } catch (SQLException e) {
        String message = "SQL error creating harvest definition " + harvestDefinition + " in database" + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(s);
        DBUtils.rollbackIfNeeded(connection, "creating", harvestDefinition);
        HarvestDBConnection.release(connection);
    }
}

From source file:orca.registry.DatabaseOperations.java

License:asdf

/**
 * Insert a new image into the database//from  w w w . jav  a 2s.com
 * @param simpleName
 * @param version
 * @param neucaVersion
 * @param imgURL
 * @param hash
 * @param owner
 * @param secription
 * @return
 */
public String insertImage(String simpleName, String version, String neucaVersion, String imgURL, String hash,
        String owner, String description, boolean isDefault) {

    if ((simpleName == null) || (version == null) || (neucaVersion == null) || (imgURL == null)
            || (hash == null) || (owner == null) || (description == null))
        return "STATUS: ERROR; invalid insert parameters";

    log.debug("Inside DatabaseOperations: insertImage() - inserting image " + simpleName);
    String status = STATUS_SUCCESS;
    Connection conn = null;

    // check for image duplicate
    if (checkImageDuplicate("img_url", imgURL)) {
        log.error("This registration is invalid, image " + simpleName + "/" + imgURL
                + " will not be allowed to register");
        return "STATUS: ERROR; duplicate image URL detected";
    }

    if (isDefault)
        undoDefaultImage();

    try {
        //System.out.println("Trying to get a new instance");
        log.debug("Inside DatabaseOperations: insert() - Trying to get a new instance");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        //System.out.println("Trying to get a database connection");
        log.debug("Inside DatabaseOperations: insert() - Trying to get a database connection");
        conn = DriverManager.getConnection(url, userName, password);
        //System.out.println ("Database connection established");
        log.debug("Inside DatabaseOperations: insert() - Database connection established");

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String insertDate = sdf.format(cal.getTime());

        PreparedStatement pStat = conn.prepareStatement(
                "INSERT into `Images` ( `img_simple_name` , `img_ver` , `img_neuca_ver`, `img_url`, `img_hash`, `img_owner`, `img_description`, `img_date`, `img_default`) values "
                        + "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
        pStat.setString(1, simpleName);
        pStat.setString(2, version);
        pStat.setString(3, neucaVersion);
        pStat.setString(4, imgURL);
        pStat.setString(5, hash);
        pStat.setString(6, owner);
        pStat.setString(7, description);
        pStat.setString(8, insertDate);
        pStat.setBoolean(9, isDefault);
        pStat.execute();
        pStat.close();
    } catch (Exception e) {
        //System.err.println ("Error inserting into Actors table");
        log.error("DatabaseOperations: insertImage() - Error inserting into Images table: " + e.toString());
        status = "STATUS: ERROR; Exception encountered during insertImage " + e;
    } finally {
        if (conn != null) {
            try {
                conn.close();
                //System.out.println ("Database connection terminated");
                log.debug("Database connection terminated");
            } catch (Exception e) { /* ignore close errors */
            }
        }
    }
    return status;
}

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

/**
 * {@inheritDoc}//w  w  w.  ja  va2 s.c  om
 */
@Override
public long getIdByLabelPath(Connection con, FxTreeMode mode, long startNode, String path)
        throws FxApplicationException {
    path = path.replaceAll("/+", "/");
    if ("/".equals(path))
        return FxTreeNode.ROOT_NODE;

    PreparedStatement ps = null;
    try {
        final DBStorage storage = StorageManager.getStorageImpl();
        ps = con.prepareStatement("SELECT tree_captionPathToID(?, ?, ?, ?, ?) " + storage.getFromDual());
        ps.setLong(1, startNode);
        ps.setString(2, path);
        ps.setLong(3, EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_CAPTION_PROPERTY));
        ps.setLong(4, FxContext.getUserTicket().getLanguage().getId());
        ps.setBoolean(5, mode == FxTreeMode.Live);

        final ResultSet rs = ps.executeQuery();
        long result = -1;
        if (rs.next()) {
            result = rs.getLong(1);
            if (rs.wasNull())
                result = -1;
        }
        return result;
    } catch (SQLException e) {
        throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (Exception e) {
            //ignore
        }
    }
}

From source file:org.apache.kylin.rest.service.QueryService.java

/**
 * @param preparedState/* w  ww .  j  ava  2  s  .c o m*/
 * @param param
 * @throws SQLException
 */
private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param)
        throws SQLException {
    boolean isNull = (null == param.getValue());

    Class<?> clazz;
    try {
        clazz = Class.forName(param.getClassName());
    } catch (ClassNotFoundException e) {
        throw new InternalErrorException(e);
    }

    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 ? 0 : Integer.valueOf(param.getValue()));
        break;
    case PRIMITIVE_SHORT:
    case SHORT:
        preparedState.setShort(index, isNull ? 0 : Short.valueOf(param.getValue()));
        break;
    case PRIMITIVE_LONG:
    case LONG:
        preparedState.setLong(index, isNull ? 0 : Long.valueOf(param.getValue()));
        break;
    case PRIMITIVE_FLOAT:
    case FLOAT:
        preparedState.setFloat(index, isNull ? 0 : Float.valueOf(param.getValue()));
        break;
    case PRIMITIVE_DOUBLE:
    case DOUBLE:
        preparedState.setDouble(index, isNull ? 0 : Double.valueOf(param.getValue()));
        break;
    case PRIMITIVE_BOOLEAN:
    case BOOLEAN:
        preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue()));
        break;
    case PRIMITIVE_BYTE:
    case BYTE:
        preparedState.setByte(index, isNull ? 0 : 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());
    }
}

From source file:org.geowebcache.storage.jdbc.jobstore.JDBCJobWrapper.java

public void putJob(JobObject stObj) throws SQLException, StorageException {

    String query = "MERGE INTO " + "JOBS(job_id, layer_name, state, time_spent, time_remaining, tiles_done, "
            + "tiles_total, failed_tile_count, bounds, gridset_id, srs, thread_count, "
            + "zoom_start, zoom_stop, format, job_type, throughput, max_throughput, "
            + "priority, schedule, run_once, spawned_by, filter_update, parameters, "
            + "time_first_start, time_latest_start, time_finish) " + "KEY(job_id) "
            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    final Connection conn = getConnection();

    try {//from   w w w.  j  av a  2s  .  co  m
        Long insertId;
        PreparedStatement prep = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        try {
            if (stObj.getJobId() == -1) {
                prep.setNull(1, java.sql.Types.BIGINT);
            } else {
                prep.setLong(1, stObj.getJobId());
            }

            prep.setString(2, stObj.getLayerName());
            prep.setString(3, stObj.getState().name());
            prep.setLong(4, stObj.getTimeSpent());
            prep.setLong(5, stObj.getTimeRemaining());
            prep.setLong(6, stObj.getTilesDone());
            prep.setLong(7, stObj.getTilesTotal());
            prep.setLong(8, stObj.getFailedTileCount());

            prep.setString(9, stObj.getBounds().toString());
            prep.setString(10, stObj.getGridSetId());
            prep.setInt(11, stObj.getSrs().getNumber());

            prep.setInt(12, stObj.getThreadCount());
            prep.setInt(13, stObj.getZoomStart());
            prep.setInt(14, stObj.getZoomStop());
            prep.setString(15, stObj.getFormat());
            prep.setString(16, stObj.getJobType().name());
            prep.setFloat(17, stObj.getThroughput());
            prep.setInt(18, stObj.getMaxThroughput());
            prep.setString(19, stObj.getPriority().name());
            prep.setString(20, stObj.getSchedule());
            prep.setBoolean(21, stObj.isRunOnce());
            prep.setLong(22, stObj.getSpawnedBy());
            prep.setBoolean(23, stObj.isFilterUpdate());
            prep.setString(24, stObj.getEncodedParameters());

            prep.setTimestamp(25, stObj.getTimeFirstStart());
            prep.setTimestamp(26, stObj.getTimeLatestStart());
            prep.setTimestamp(27, stObj.getTimeFinish());

            insertId = wrappedInsert(prep);
        } finally {
            close(prep);
        }
        if (insertId == null) {
            log.error("Did not receive an id for " + query);
        } else {
            if (stObj.getJobId() == -1) {
                // only use the inserted id if we were doing an insert.
                // what insertid will be if we weren't doing an insert is not defined.
                stObj.setJobId(insertId.longValue());
            }
        }

        putRecentJobLogs(stObj, conn);

    } finally {
        conn.close();
    }
}

From source file:org.methodize.nntprss.feed.db.JdbcChannelDAO.java

public void saveConfiguration(ChannelManager channelManager) {
    Connection conn = null;//from w ww  .  j av a  2  s. co  m
    PreparedStatement ps = null;

    try {
        conn = DriverManager.getConnection(JdbcChannelDAO.POOL_CONNECT_STRING);
        ps = conn.prepareStatement("UPDATE " + TABLE_CONFIG + " " + "SET pollingInterval = ?, "
                + "proxyServer = ?, " + "proxyPort = ?, " + "proxyUserID = ?, " + "proxyPassword = ?, "
                + "useProxy = ?, " + "observeHttp301 = ?");

        int paramCount = 1;
        ps.setLong(paramCount++, channelManager.getPollingIntervalSeconds());
        ps.setString(paramCount++, channelManager.getProxyServer());
        ps.setInt(paramCount++, channelManager.getProxyPort());
        ps.setString(paramCount++, channelManager.getProxyUserID());
        ps.setString(paramCount++, channelManager.getProxyPassword());
        ps.setBoolean(paramCount++, channelManager.isUseProxy());
        ps.setBoolean(paramCount++, channelManager.isObserveHttp301());
        ps.executeUpdate();

    } catch (SQLException se) {
        throw new RuntimeException(se);
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException se) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
        }
    }

}