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.lucene.store.jdbc.JdbcDirectory.java

/**
 * Delets all the file entries that are marked to be deleted, and they were marked
 * "delta" time ago (base on database time, if possible by dialect).
 *//*from  w w  w .  java 2  s  .co m*/
public void deleteMarkDeleted(long delta) throws IOException {
    long currentTime = System.currentTimeMillis();
    if (dialect.supportsCurrentTimestampSelection()) {
        String timestampSelectString = dialect.getCurrentTimestampSelectString();
        if (dialect.isCurrentTimestampSelectStringCallable()) {
            currentTime = ((Long) jdbcTemplate.executeCallable(timestampSelectString,
                    new JdbcTemplate.CallableStatementCallback() {
                        public void fillCallableStatement(CallableStatement cs) throws Exception {
                            cs.registerOutParameter(1, java.sql.Types.TIMESTAMP);
                        }

                        public Object readCallableData(CallableStatement cs) throws Exception {
                            Timestamp timestamp = cs.getTimestamp(1);
                            return new Long(timestamp.getTime());
                        }
                    })).longValue();
        } else {
            currentTime = ((Long) jdbcTemplate.executeSelect(timestampSelectString,
                    new JdbcTemplate.ExecuteSelectCallback() {
                        public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                            // nothing to do here
                        }

                        public Object execute(ResultSet rs) throws Exception {
                            rs.next();
                            Timestamp timestamp = rs.getTimestamp(1);
                            return new Long(timestamp.getTime());
                        }
                    })).longValue();
        }
    }
    final long deleteBefore = currentTime - delta;
    jdbcTemplate.executeUpdate(table.sqlDeletaMarkDeleteByDelta(),
            new JdbcTemplate.PrepateStatementAwareCallback() {
                public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                    ps.setBoolean(1, true);
                    ps.setTimestamp(2, new Timestamp(deleteBefore));
                }
            });
}

From source file:com.salesmanager.core.service.catalog.impl.db.dao.CategoryDao.java

public void save(final Category instance) {
    getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Connection con = session.connection();
            PreparedStatement ps = con
                    .prepareStatement("insert into categories(categories_id,categories_image,parent_id,"
                            + "sort_order,date_added,last_modified,categories_status,visible,RefCategoryID,"
                            + "RefCategoryLevel,RefCategoryName,RefCategoryParentID,RefExpired,merchantid,depth,"
                            + "lineage) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            ps.setLong(1, instance.getCategoryId());
            ps.setString(2, instance.getCategoryImage());
            ps.setLong(3, instance.getParentId());
            ps.setInt(4, (instance.getSortOrder() == null ? 0 : instance.getSortOrder()));
            ps.setDate(5, new java.sql.Date(instance.getDateAdded().getTime()));
            ps.setDate(6, new java.sql.Date(instance.getLastModified().getTime()));
            ps.setBoolean(7, instance.isCategoryStatus());
            ps.setBoolean(8, instance.isVisible());
            ps.setLong(9, instance.getRefCategoryId());
            ps.setInt(10, instance.getRefCategoryLevel());
            ps.setString(11, instance.getRefCategoryName());
            ps.setString(12, instance.getRefCategoryParentId());
            ps.setString(13, instance.getRefExpired());
            ps.setLong(14, instance.getMerchantId());
            ps.setInt(15, instance.getDepth());
            ps.setString(16, instance.getLineage());
            return ps.executeUpdate();
        }/*from  w w w.  j  a v a  2  s.c om*/

    });
}

From source file:admin.controller.Layout.java

public void addLayouts(Integer organization_id, Integer user_id, Integer category_id, String layout,
        String model, boolean email, boolean social, Integer sub_category_id, Integer brand_id,
        Integer block_id, String Style_image_name, String file_name) throws SQLException {
    String query_string = "";
    PreparedStatement prepared_statement = null;
    ResultSet result_set = null;/*from  w w w.ja  v  a  2 s. c  o m*/

    try (Connection connection = ConnectionManager.getInstance().getConnection()) {
        query_string = "Insert into tbl_model (organization_id, user_id, category_id, layout_file_name, model_file_name, email, social, sub_category_id, brand_id, block_id,image_file_name, model_name) values(?,?,?,?,?,?,?,?,?,?,?,?)";

        prepared_statement = connection.prepareStatement(query_string);
        prepared_statement.setInt(1, organization_id);
        prepared_statement.setInt(2, user_id);
        prepared_statement.setInt(3, category_id);
        prepared_statement.setString(4, layout);
        prepared_statement.setString(5, model);
        prepared_statement.setBoolean(6, email);
        prepared_statement.setBoolean(7, social);
        prepared_statement.setInt(8, sub_category_id);
        prepared_statement.setInt(9, brand_id);
        prepared_statement.setInt(10, block_id);
        prepared_statement.setString(11, Style_image_name);
        prepared_statement.setString(12, file_name);
        prepared_statement.executeUpdate();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "", e);
    } finally {
        sqlmethods.close(result_set, prepared_statement);

    }

}

From source file:com.act.lcms.db.model.MS1ScanForWellAndMassCharge.java

protected void bindInsertOrUpdateParameters(PreparedStatement stmt, Integer plateId, Integer plateRow,
        Integer plateColumn, Boolean useSNR, String lcmsScanFileDir, String chemicalName,
        List<String> metlinIons, Map<String, List<XZ>> ionsToSpectra, Map<String, Double> ionsToIntegral,
        Map<String, Double> ionsToMax, Map<String, Double> ionsToLogSNR, Map<String, Double> ionsToAvgSignal,
        Map<String, Double> ionsToAvgAmbient, Map<String, Double> individualMaxIntensities, Double maxYAxis)
        throws SQLException, IOException {
    stmt.setInt(DB_FIELD.PLATE_ID.getInsertUpdateOffset(), plateId);
    stmt.setInt(DB_FIELD.PLATE_ROW.getInsertUpdateOffset(), plateRow);
    stmt.setInt(DB_FIELD.PLATE_COLUMN.getInsertUpdateOffset(), plateColumn);
    stmt.setBoolean(DB_FIELD.USE_SNR.getInsertUpdateOffset(), useSNR);
    stmt.setString(DB_FIELD.SCAN_FILE.getInsertUpdateOffset(), lcmsScanFileDir);
    stmt.setString(DB_FIELD.CHEMICAL_NAME.getInsertUpdateOffset(), chemicalName);
    stmt.setString(DB_FIELD.METLIN_IONS.getInsertUpdateOffset(), OBJECT_MAPPER.writeValueAsString(metlinIons));
    stmt.setBytes(DB_FIELD.IONS_TO_SPECTRA.getInsertUpdateOffset(), serialize(ionsToSpectra));
    stmt.setBytes(DB_FIELD.IONS_TO_INTEGRAL.getInsertUpdateOffset(), serialize(ionsToIntegral));
    stmt.setBytes(DB_FIELD.IONS_TO_LOG_SNR.getInsertUpdateOffset(), serialize(ionsToLogSNR));
    stmt.setBytes(DB_FIELD.IONS_TO_AVG_AMBIENT.getInsertUpdateOffset(), serialize(ionsToAvgAmbient));
    stmt.setBytes(DB_FIELD.IONS_TO_AVG_SIGNAL.getInsertUpdateOffset(), serialize(ionsToAvgSignal));
    stmt.setBytes(DB_FIELD.INDIVIDUAL_MAX_INTENSITIES.getInsertUpdateOffset(),
            serialize(individualMaxIntensities));
    stmt.setBytes(DB_FIELD.IONS_TO_MAX.getInsertUpdateOffset(), serialize(ionsToMax));
    stmt.setDouble(DB_FIELD.MAX_Y_AXIS.getInsertUpdateOffset(), maxYAxis);
}

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

@Override
public void save(Penalty penalty) {
    String sql;/*  ww w.j ava2  s.c o m*/
    if (penalty.getKey() == null) {
        sql = "insert into penalty (playerid, adminid, type, reason, duration, synced, active, created, updated, expires) values (?,?,?,?,?,?,?,?,?,?)";
    } else {
        sql = "update penalty set playerid = ?," + "adminid = ?," + "type = ?," + "reason = ?,"
                + "duration = ?," + "synced = ?," + "active = ?," + "created = ?," + "updated = ?,"
                + "expires = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setLong(1, penalty.getPlayer());
        if (penalty.getAdmin() != null)
            st.setLong(2, penalty.getAdmin());
        else
            st.setNull(2, Types.INTEGER);
        st.setInt(3, penalty.getType().intValue());
        if (penalty.getReason() != null)
            st.setString(4, penalty.getReason());
        else
            st.setNull(4, Types.VARCHAR);
        if (penalty.getDuration() == null)
            penalty.setDuration(0L);
        st.setLong(5, penalty.getDuration());
        st.setBoolean(6, penalty.getSynced());
        st.setBoolean(7, penalty.getActive());
        if (penalty.getCreated() == null)
            penalty.setCreated(new Date());
        if (penalty.getUpdated() == null)
            penalty.setUpdated(new Date());
        st.setTimestamp(8, new java.sql.Timestamp(penalty.getCreated().getTime()));
        st.setTimestamp(9, new java.sql.Timestamp(penalty.getUpdated().getTime()));
        st.setTimestamp(10, new java.sql.Timestamp(
                DateUtils.addMinutes(penalty.getCreated(), penalty.getDuration().intValue()).getTime()));
        if (penalty.getKey() != null)
            st.setLong(11, penalty.getKey());
        st.executeUpdate();
        if (penalty.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                penalty.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for penalty player id {}", penalty.getPlayer());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:mupomat.controller.ObradaKorisnik.java

@Override
public Korisnik dodajNovi(Korisnik entitet) {

    try {// w  ww . j av a  2 s  .c  om
        Connection veza = MySqlBazaPodataka.getConnection();

        veza.setAutoCommit(false);

        PreparedStatement izraz = veza
                .prepareStatement("insert into osoba (oib,ime,prezime,email) values (?,?,?,?)");
        izraz.setString(1, entitet.getOib());
        izraz.setString(2, entitet.getIme());
        izraz.setString(3, entitet.getPrezime());
        izraz.setString(4, entitet.getEmail());
        izraz.executeUpdate();

        izraz = veza.prepareStatement(
                "insert into korisnik (oib,automat,datumregistracije,korisnickoime,lozinka,uloga,aktivan) values (?,?,now(),?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        izraz.setString(1, entitet.getOib());
        izraz.setString(2, entitet.getAutomat());
        izraz.setString(3, entitet.getKorisnickoIme());
        izraz.setString(4, DigestUtils.md5Hex(entitet.getLozinka()));
        izraz.setString(5, entitet.getUloga());
        izraz.setBoolean(6, entitet.isAktivan());
        izraz.executeUpdate();

        ResultSet rs = izraz.getGeneratedKeys();
        rs.next();
        entitet.setSifra(rs.getInt(1));

        izraz.close();
        veza.commit();
        veza.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        return null;
    }

    return entitet;
}

From source file:hoot.services.db.DbUtils.java

public static void batchRecordsDirectWays(final long mapId, final List<?> records,
        final RecordBatchType recordBatchType, Connection conn, int maxRecordBatchSize) throws Exception {
    PreparedStatement ps = null;
    try {//from   ww w.j a  va2 s.c  o m
        String sql = null;
        long execResult = -1;
        //conn.setAutoCommit(false);
        int count = 0;

        switch (recordBatchType) {
        case INSERT:

            sql = "insert into current_ways_" + mapId
                    + " (id, changeset_id, \"timestamp\", visible, version, tags) "
                    + "values (?, ?, ?, ?, ?, ?)";

            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentWays way = (CurrentWays) o;

                ps.setLong(1, way.getId());
                ps.setLong(2, way.getChangesetId());
                ps.setTimestamp(3, way.getTimestamp());
                ps.setBoolean(4, way.getVisible());
                ps.setLong(5, way.getVersion());

                Map<String, String> tags = (Map<String, String>) way.getTags();

                String hstoreStr = "";
                Iterator it = tags.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry) it.next();
                    if (hstoreStr.length() > 0) {
                        hstoreStr += ",";
                    }
                    hstoreStr += "\"" + pairs.getKey() + "\"=>\"" + pairs.getValue() + "\"";
                }
                ps.setObject(6, hstoreStr, Types.OTHER);
                ps.addBatch();

                if (maxRecordBatchSize > -1) {
                    if (++count % maxRecordBatchSize == 0) {
                        ps.executeBatch();
                        //conn.commit();
                    }
                }

            }

            break;

        case UPDATE:

            sql = "update current_ways_" + mapId
                    + " set changeset_id=?, visible=?, \"timestamp\"=?, version=?, tags=? " + "where id=?";
            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentWays way = (CurrentWays) o;

                ps.setLong(1, way.getChangesetId());
                ps.setBoolean(2, way.getVisible());
                ps.setTimestamp(3, way.getTimestamp());
                ps.setLong(4, way.getVersion());

                Map<String, String> tags = (Map<String, String>) way.getTags();

                String hstoreStr = "";
                Iterator it = tags.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry) it.next();
                    if (hstoreStr.length() > 0) {
                        hstoreStr += ",";
                    }
                    hstoreStr += "\"" + pairs.getKey() + "\"=>\"" + pairs.getValue() + "\"";
                }
                ps.setObject(5, hstoreStr, Types.OTHER);

                ps.setLong(6, way.getId());

                ps.addBatch();

                if (maxRecordBatchSize > -1) {
                    if (++count % maxRecordBatchSize == 0) {
                        ps.executeBatch();
                        //conn.commit();
                    }
                }
            }

            break;

        case DELETE:

            sql = "delete from current_ways_" + mapId + " where id=?";
            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentWays way = (CurrentWays) o;

                ps.setLong(1, way.getId());

                ps.addBatch();

                if (maxRecordBatchSize > -1) {
                    if (++count % maxRecordBatchSize == 0) {
                        ps.executeBatch();
                        //conn.commit();
                    }
                }

            }

            break;

        default:
            throw new Exception("");
        }

        ps.executeBatch();
        //conn.commit();
    } catch (Exception e) {
        conn.rollback();
        String msg = "Error executing batch query.";
        msg += "  " + e.getMessage();
        msg += " Cause:" + e.getCause().toString();
        throw new Exception(msg);
    } finally {
        if (ps != null) {
            ps.close();
        }
        //conn.setAutoCommit(true);
    }
}

From source file:com.googlecode.fascinator.portal.HouseKeeper.java

/**
 * Store a new action in the database and update the action queue.
 * /*from w  w  w  .  ja  v a2  s  .co  m*/
 * @param action The User action to store
 */
private void storeAction(UserAction action) {
    // Don't store duplicates
    if (isCurrentAction(action.message)) {
        return;
    }
    // Capture the current time
    if (action.date == null) {
        action.date = new Date();
    }
    // Otherwise proceed as normal
    try {
        log.debug("Storing action: '{}'", action.message);
        // Prepare our query
        PreparedStatement sql = dbConnection().prepareCall(
                "INSERT INTO " + NOTIFICATIONS_TABLE + " (block, message, datetime) VALUES (?, ?, ?)");
        // Run the query
        sql.setBoolean(1, action.block);
        sql.setString(2, action.message);
        sql.setTimestamp(3, new Timestamp(action.date.getTime()));
        sql.executeUpdate();
        close(sql);
        // Update memory cache
        syncActionList();
    } catch (SQLException ex) {
        log.error("Error accessing database: ", ex);
    }
}

From source file:hoot.services.db.DbUtils.java

public static void batchRecordsDirectRelations(final long mapId, final List<?> records,
        final RecordBatchType recordBatchType, Connection conn, int maxRecordBatchSize) throws Exception {
    PreparedStatement ps = null;
    try {/*from w  w  w .ja v  a  2 s  .  c o m*/
        String sql = null;
        long execResult = -1;
        //conn.setAutoCommit(false);
        int count = 0;

        switch (recordBatchType) {
        case INSERT:

            sql = "insert into current_relations_" + mapId
                    + " (id, changeset_id, \"timestamp\", visible, version, tags) "
                    + "values (?, ?, ?, ?, ?, ?)";

            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentRelations rel = (CurrentRelations) o;

                ps.setLong(1, rel.getId());
                ps.setLong(2, rel.getChangesetId());
                ps.setTimestamp(3, rel.getTimestamp());
                ps.setBoolean(4, rel.getVisible());
                ps.setLong(5, rel.getVersion());

                Map<String, String> tags = (Map<String, String>) rel.getTags();

                String hstoreStr = "";
                Iterator it = tags.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry) it.next();
                    if (hstoreStr.length() > 0) {
                        hstoreStr += ",";
                    }
                    hstoreStr += "\"" + pairs.getKey() + "\"=>\"" + pairs.getValue() + "\"";
                }
                ps.setObject(6, hstoreStr, Types.OTHER);
                ps.addBatch();

                if (maxRecordBatchSize > -1) {
                    if (++count % maxRecordBatchSize == 0) {
                        ps.executeBatch();
                        //conn.commit();
                    }
                }

            }

            break;

        case UPDATE:

            sql = "update current_relations_" + mapId
                    + " set changeset_id=?, visible=?, \"timestamp\"=?, version=?, tags=? " + "where id=?";
            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentRelations rel = (CurrentRelations) o;

                ps.setLong(1, rel.getChangesetId());
                ps.setBoolean(2, rel.getVisible());
                ps.setTimestamp(3, rel.getTimestamp());
                ps.setLong(4, rel.getVersion());

                Map<String, String> tags = (Map<String, String>) rel.getTags();

                String hstoreStr = "";
                Iterator it = tags.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry) it.next();
                    if (hstoreStr.length() > 0) {
                        hstoreStr += ",";
                    }
                    hstoreStr += "\"" + pairs.getKey() + "\"=>\"" + pairs.getValue() + "\"";
                }
                ps.setObject(5, hstoreStr, Types.OTHER);

                ps.setLong(6, rel.getId());

                ps.addBatch();

                if (maxRecordBatchSize > -1) {
                    if (++count % maxRecordBatchSize == 0) {
                        ps.executeBatch();
                        //conn.commit();
                    }
                }
            }

            break;

        case DELETE:

            sql = "delete from current_relations_" + mapId + " where id=?";
            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentRelations rel = (CurrentRelations) o;

                ps.setLong(1, rel.getId());

                ps.addBatch();

                if (maxRecordBatchSize > -1) {
                    if (++count % maxRecordBatchSize == 0) {
                        ps.executeBatch();
                        //conn.commit();
                    }
                }

            }

            break;

        default:
            throw new Exception("");
        }

        ps.executeBatch();
        //conn.commit();
    } catch (Exception e) {
        conn.rollback();
        String msg = "Error executing batch query.";
        msg += "  " + e.getMessage();
        msg += " Cause:" + e.getCause().toString();
        throw new Exception(msg);
    } finally {
        if (ps != null) {
            ps.close();
        }
        //conn.setAutoCommit(true);
    }
}