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:com.flexive.ejb.beans.PhraseEngineBean.java

/**
 * {@inheritDoc}/*  w  w w .  j a v  a2s .  c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setPhraseHidden(int category, String phraseKey, long mandator, boolean hidden)
        throws FxNoAccessException {
    Connection con = null;
    PreparedStatement ps = null;
    final UserTicket userTicket = FxContext.getUserTicket();
    checkMandatorAccess(mandator, userTicket);
    checkPhraseKey(phraseKey);
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        ps = con.prepareStatement("UPDATE " + TBL_PHRASE + " SET HID=? WHERE PKEY=? AND MANDATOR=? AND CAT=?");
        ps.setBoolean(1, hidden);
        ps.setString(2, phraseKey);
        ps.setLong(3, mandator);
        ps.setInt(4, category);
        ps.executeUpdate();
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(PhraseEngineBean.class, con, ps);
    }
}

From source file:org.apache.torque.util.BasePeerImpl.java

/**
 * Sets the prepared statement replacements into a query, possibly
 * modifying the type if required by DB Drivers.
 *
 * @param statement the statement to set the parameters in, not null.
 * @param replacements the replacements to set, not null.
 * @param offset the offset on the parameters, 0 for no offset.
 *
 * @return the parameters set.//from  ww w  .  j av a2  s . c  o  m
 *
 * @throws SQLException if setting the parameter fails.
 */
private List<Object> setPreparedStatementReplacements(PreparedStatement statement, List<Object> replacements,
        int offset) throws SQLException {
    List<Object> result = new ArrayList<Object>(replacements.size());
    int i = 1 + offset;
    for (Object param : replacements) {
        if (param instanceof java.sql.Timestamp) {
            statement.setTimestamp(i, (java.sql.Timestamp) param);
            result.add(param);
        } else if (param instanceof java.sql.Date) {
            statement.setDate(i, (java.sql.Date) param);
            result.add(param);
        } else if (param instanceof java.util.Date) {
            java.sql.Timestamp sqlDate = new java.sql.Timestamp(((java.util.Date) param).getTime());
            statement.setTimestamp(i, sqlDate);
            result.add(sqlDate);
        } else if (param instanceof NumberKey) {
            BigDecimal bigDecimal = ((NumberKey) param).getBigDecimal();
            statement.setBigDecimal(i, bigDecimal);
            result.add(bigDecimal);
        } else if (param instanceof Integer) {
            statement.setInt(i, ((Integer) param).intValue());
            result.add(param);
        } else if (param instanceof Long) {
            statement.setLong(i, ((Long) param).longValue());
            result.add(param);
        } else if (param instanceof BigDecimal) {
            statement.setBigDecimal(i, (BigDecimal) param);
            result.add(param);
        } else if (param instanceof Boolean) {
            statement.setBoolean(i, ((Boolean) param).booleanValue());
            result.add(param);
        } else {
            statement.setString(i, param.toString());
            result.add(param.toString());
        }
        ++i;
    }
    return result;
}

From source file:org.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java

private void createStreamItem(String activityId, String ownerId, String posterId, String viewerId,
        String viewerType, Boolean hidable, Boolean lockable, Long time) {
    //insert to mysql stream_item table
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    StringBuilder insertTableSQL = new StringBuilder();
    insertTableSQL.append("INSERT INTO stream_item")
            .append("(_id, activityId, ownerId, posterId, viewerId, viewerType,")
            .append("hidable, lockable, time)").append("VALUES (?,?,?,?,?,?,?,?,?)");

    try {// w  w w  .  j av  a  2 s.c o  m
        dbConnection = dbConnect.getDBConnection();
        preparedStatement = dbConnection.prepareStatement(insertTableSQL.toString());
        preparedStatement.setString(1, UUID.randomUUID().toString());
        preparedStatement.setString(2, activityId);
        preparedStatement.setString(3, ownerId);
        preparedStatement.setString(4, posterId);
        preparedStatement.setString(5, viewerId);
        preparedStatement.setString(6, viewerType);
        preparedStatement.setBoolean(7, hidable);
        preparedStatement.setBoolean(8, lockable);
        preparedStatement.setLong(9, time);

        preparedStatement.executeUpdate();

        LOG.debug("new stream item created");

    } catch (SQLException e) {

        LOG.error("error in stream item creation:", e.getMessage());

    } finally {
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }
        } catch (SQLException e) {
            LOG.error("Cannot close statement or connection:", e.getMessage());
        }
    }

}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

@Test
public void testPrepareStatement() {

    String sql = "from (select count(1) from " + tableName
            + " where   'not?param?not?param' <> 'not_param??not_param' and ?=? "
            + " and 1=? and 2=? and 3.0=? and 4.0=? and 'test\\'string\"'=? and 5=? and ?=? "
            + " and date '2012-01-01' = date ?"
            + " ) t  select '2011-03-25' ddate,'China',true bv, 10 num limit 10";

    ///////////////////////////////////////////////
    //////////////////// correct testcase
    //////////////////// executed twice: once with the typed ps setters, once with the generic setObject
    //////////////////////////////////////////////
    try {//from w ww. j  a v a  2s. c  o m
        PreparedStatement ps = createPreapredStatementUsingSetXXX(sql);
        ResultSet res = ps.executeQuery();
        assertPreparedStatementResultAsExpected(res);
        ps.close();

        ps = createPreapredStatementUsingSetObject(sql);
        res = ps.executeQuery();
        assertPreparedStatementResultAsExpected(res);
        ps.close();

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.toString());
    }

    ///////////////////////////////////////////////
    //////////////////// other failure testcases
    //////////////////////////////////////////////
    // set nothing for prepared sql
    Exception expectedException = null;
    try {
        PreparedStatement ps = con.prepareStatement(sql);
        ps.executeQuery();
    } catch (Exception e) {
        expectedException = e;
    }
    assertNotNull("Execute the un-setted sql statement should throw exception", expectedException);

    // set some of parameters for prepared sql, not all of them.
    expectedException = null;
    try {
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setBoolean(1, true);
        ps.setBoolean(2, true);
        ps.executeQuery();
    } catch (Exception e) {
        expectedException = e;
    }
    assertNotNull("Execute the invalid setted sql statement should throw exception", expectedException);

    // set the wrong type parameters for prepared sql.
    expectedException = null;
    try {
        PreparedStatement ps = con.prepareStatement(sql);

        // wrong type here
        ps.setString(1, "wrong");

        assertTrue(true);
        ResultSet res = ps.executeQuery();
        if (!res.next()) {
            throw new Exception("there must be a empty result set");
        }
    } catch (Exception e) {
        expectedException = e;
    }
    assertNotNull("Execute the invalid setted sql statement should throw exception", expectedException);

    // setObject to the yet unknown type java.util.Date
    expectedException = null;
    try {
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, new Date());
        ps.executeQuery();
    } catch (Exception e) {
        expectedException = e;
    }
    assertNotNull("Setting to an unknown type should throw an exception", expectedException);

}

From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java

/**
 * Sets the designated parameter to the given Java <code>boolean</code> value.
 * This just wraps <code>{@link PreparedStatement#setBoolean(int, boolean)}</code>
 * by default, but it can be overloaded by subclass delegates for databases that
 * don't explicitly support the boolean type.
 *//*from w ww . j a v  a2  s .c o m*/
protected void setBoolean(PreparedStatement ps, int index, boolean val) throws SQLException {
    ps.setBoolean(index, val);
}

From source file:HSqlManager.java

@SuppressWarnings("Duplicates")
@Deprecated/*from   www. ja va 2 s . c om*/
public static void mycoUniqueDB(Connection connection, int bps) throws ClassNotFoundException, SQLException,
        InstantiationException, IllegalAccessException, IOException {
    long time = System.currentTimeMillis();
    DpalLoad.main(new String[1]);
    HSqlPrimerDesign.Dpal_Inst = DpalLoad.INSTANCE_WIN64;
    String base = new File("").getAbsolutePath();
    if (!written) {
        CSV.makeDirectory(new File(base + "/PhageData"));
        INSTANCE.parseAllPhages(bps);
    }
    Connection db = connection;
    db.setAutoCommit(false);
    Statement stat = db.createStatement();
    PrintWriter log = new PrintWriter(new File("javalog.log"));
    stat.execute("SET FILES LOG FALSE;\n");
    PreparedStatement st = db
            .prepareStatement("UPDATE Primerdb.Primers" + " SET UniqueP = true, Tm = ?, GC =?, Hairpin =?"
                    + "WHERE Cluster = ? and Strain = ? and " + "Sequence = ? and Bp = ?");
    ResultSet call = stat.executeQuery("Select * From Primerdb.Phages;");
    List<String[]> phages = new ArrayList<>();
    String strain = "";
    while (call.next()) {
        String[] r = new String[3];
        r[0] = call.getString("Strain");
        r[1] = call.getString("Cluster");
        r[2] = call.getString("Name");
        phages.add(r);
        if (r[2].equals("xkcd")) {
            strain = r[0];
        }
    }
    call.close();
    String x = strain;
    Set<String> clust = phages.stream().filter(y -> y[0].equals(x)).map(y -> y[1]).collect(Collectors.toSet());
    String[] clusters = clust.toArray(new String[clust.size()]);
    for (String z : clusters) {
        try {
            Set<String> nonclustphages = phages.stream().filter(a -> a[0].equals(x) && !a[1].equals(z))
                    .map(a -> a[2]).collect(Collectors.toSet());
            ResultSet resultSet = stat.executeQuery(
                    "Select Sequence from primerdb.primers" + " where Strain ='" + x + "' and Cluster ='" + z
                            + "' and CommonP = true" + " and Bp = " + Integer.valueOf(bps) + " ");
            Set<CharSequence> primers = Collections.synchronizedSet(new HashSet<>());
            while (resultSet.next()) {
                primers.add(resultSet.getString("Sequence"));
            }
            resultSet.close();
            for (String phage : nonclustphages) {
                //                    String[] seqs = Fasta.parse(base + "/Fastas/" + phage + ".fasta");
                //                    String sequence =seqs[0]+seqs[1];
                //                        Map<String, List<Integer>> seqInd = new HashMap<>();
                //                        for (int i = 0; i <= sequence.length()-bps; i++) {
                //                            String sub=sequence.substring(i,i+bps);
                //                            if(seqInd.containsKey(sub)){
                //                                seqInd.get(sub).add(i);
                //                            }else {
                //                                List<Integer> list = new ArrayList<>();
                //                                list.add(i);
                //                                seqInd.put(sub,list);
                //                            }
                //                        }
                //                    primers = primers.stream().filter(primer->!seqInd.containsKey(primer)).collect(Collectors.toSet());
                //                    primers =Sets.difference(primers,CSV.readCSV(base + "/PhageData/"+Integer.toString(bps)
                //                                    + phage + ".csv"));
                CSV.readCSV(base + "/PhageData/" + Integer.toString(bps) + phage + ".csv").stream()
                        .filter(primers::contains).forEach(primers::remove);
                //                    System.gc();

            }
            int i = 0;
            for (CharSequence a : primers) {
                try {
                    st.setDouble(1, HSqlPrimerDesign.primerTm(a, 0, 800, 1.5, 0.2));
                    st.setDouble(2, HSqlPrimerDesign.gcContent(a));
                    st.setBoolean(3, HSqlPrimerDesign.calcHairpin((String) a, 4));
                    st.setString(4, z);
                    st.setString(5, x);
                    st.setString(6, a.toString());
                    st.setInt(7, bps);
                    st.addBatch();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("Error occurred at " + x + " " + z);
                }
                i++;
                if (i == 1000) {
                    i = 0;
                    st.executeBatch();
                    db.commit();
                }
            }
            if (i > 0) {
                st.executeBatch();
                db.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Error occurred at " + x + " " + z);
        }
        log.println(z);
        log.flush();
        System.gc();
    }
    stat.execute("SET FILES LOG TRUE\n");
    st.close();
    stat.close();
    System.out.println("Unique Updated");
    System.out.println((System.currentTimeMillis() - time) / Math.pow(10, 3) / 60);
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private int fillEventStatement(PreparedStatement ps, Event ev, AccessToken at, int i) throws SQLException {
    int idx = i;//from ww w .  j  ava2 s .  c  om
    ps.setString(idx++, ev.getExtId().getExtId());
    ps.setString(idx++, ev.getTimezoneName());
    ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VOPACITY, ev.getOpacity().toString()));
    ps.setString(idx++, ev.getTitle());
    ps.setString(idx++, ev.getLocation());
    Integer cat = catIdFromString(ps.getConnection(), ev.getCategory(), at.getDomain().getId());
    if (cat != null) {
        ps.setInt(idx++, cat);
    } else {
        ps.setNull(idx++, Types.INTEGER);
    }
    ps.setInt(idx++, RFC2445.getPriorityOrDefault(ev.getPriority()));
    ps.setInt(idx++, ev.getPrivacy().toInteger());
    if (ev.getStartDate() != null) {
        ps.setTimestamp(idx++, new Timestamp(ev.getStartDate().getTime()));
    } else {
        ps.setNull(idx++, Types.DATE);
    }
    ps.setInt(idx++, ev.getDuration());
    ps.setBoolean(idx++, ev.isAllday());
    EventRecurrence r = ev.getRecurrence();
    ps.setString(idx++, r.getKind().toString());
    ps.setInt(idx++, r.getFrequence());
    ps.setString(idx++, new RecurrenceDaysSerializer().serialize(r.getDays()));
    if (r.getEnd() != null) {
        ps.setTimestamp(idx++, new Timestamp(r.getEnd().getTime()));
    } else {
        ps.setNull(idx++, Types.DATE);
    }
    ps.setNull(idx++, Types.VARCHAR); // color
    ps.setNull(idx++, Types.DATE); // FIXME completed
    ps.setNull(idx++, Types.VARCHAR); // FIXME url
    ps.setString(idx++, ev.getDescription());
    ps.setInt(idx++, at.getDomain().getId());
    ps.setString(idx++, at.getOrigin());
    ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VCOMPONENT, ev.getType().toString()));
    ps.setInt(idx++, ev.getSequence());
    return idx;
}

From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java

private int insertIntoContact(Connection con, AccessToken at, Contact c, int addressBookId)
        throws SQLException {
    PreparedStatement ps = null;
    try {/*from ww  w .  ja  v a 2  s  .c  o  m*/

        ps = con.prepareStatement("INSERT INTO Contact "
                + " (contact_commonname, contact_firstname, contact_lastname, contact_origin, contact_domain_id, contact_usercreate, "
                + "contact_company, contact_aka, contact_service, contact_title, contact_birthday_id, contact_anniversary_id, "
                + "contact_timecreate, "
                + "contact_suffix, contact_middlename, contact_manager, contact_spouse, contact_assistant, "
                + "contact_collected, contact_addressbook_id) "
                + " VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now(), ?, ?, ?, ?, ?, ?, ?) ");
        int idx = 1;
        ps.setString(idx++, c.getCommonname());
        ps.setString(idx++, c.getFirstname());
        ps.setString(idx++, c.getLastname());
        ps.setString(idx++, at.getOrigin());
        ps.setInt(idx++, at.getDomain().getId());
        ps.setInt(idx++, at.getObmId());

        ps.setString(idx++, c.getCompany());
        ps.setString(idx++, c.getAka());
        ps.setString(idx++, c.getService());
        ps.setString(idx++, c.getTitle());
        if (c.getBirthdayId() != null) {
            ps.setInt(idx++, c.getBirthdayId().getObmId());
        } else {
            ps.setNull(idx++, Types.BIGINT);
        }
        if (c.getAnniversaryId() != null) {
            ps.setInt(idx++, c.getAnniversaryId().getObmId());
        } else {
            ps.setNull(idx++, Types.BIGINT);
        }

        ps.setString(idx++, c.getSuffix());
        ps.setString(idx++, c.getMiddlename());
        ps.setString(idx++, c.getManager());
        ps.setString(idx++, c.getSpouse());
        ps.setString(idx++, c.getAssistant());

        ps.setBoolean(idx++, c.isCollected());
        ps.setInt(idx++, addressBookId);

        ps.executeUpdate();

        int contactId = obmHelper.lastInsertId(con);

        return contactId;

    } finally {
        obmHelper.cleanup(null, ps, null);
    }
}

From source file:org.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java

private int fillPreparedStatementFromActivity(Identity owner, ExoSocialActivity activity,
        PreparedStatement preparedStatement, int index) throws SQLException {
    preparedStatement.setString(index++, activity.getTitle());
    preparedStatement.setString(index++, activity.getTitleId());
    preparedStatement.setString(index++, activity.getBody());
    preparedStatement.setString(index++, activity.getBodyId());
    preparedStatement.setLong(index++, activity.getPostedTime());
    preparedStatement.setLong(index++, activity.getUpdated().getTime());
    preparedStatement.setString(index++, activity.getPosterId());
    preparedStatement.setString(index++, owner.getRemoteId());
    preparedStatement.setString(index++, owner.getId());
    preparedStatement.setString(index++, activity.getPermaLink());
    preparedStatement.setString(index++, activity.getAppId());
    preparedStatement.setString(index++, activity.getExternalId());
    if (activity.getPriority() == null) {
        preparedStatement.setNull(index++, Types.FLOAT);
    } else {// w ww .  j  a  v  a 2 s .com
        preparedStatement.setFloat(index++, activity.getPriority());
    }
    preparedStatement.setBoolean(index++, activity.isHidden());
    preparedStatement.setBoolean(index++, activity.isLocked());
    preparedStatement.setString(index++, StringUtils.join(activity.getLikeIdentityIds(), ","));
    preparedStatement.setString(index++, StringUtils.join(activity.getMentionedIds(), ","));
    preparedStatement.setString(index++, StringUtils.join(activity.getCommentedIds(), ","));
    preparedStatement.setString(index++, StringUtils.join(activity.getReplyToId(), ","));
    preparedStatement.setString(index++, null);
    //
    if (activity.getTemplateParams() != null) {
        try {
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            ObjectOutputStream output = new ObjectOutputStream(b);
            output.writeObject(activity.getTemplateParams());
            preparedStatement.setBinaryStream(index++, new ByteArrayInputStream(b.toByteArray()));
        } catch (IOException e) {
            LOG.debug("Failed to save templateParams of activity into database");
        }
    } else {
        preparedStatement.setNull(index++, Types.BLOB);
    }
    preparedStatement.setString(index++, activity.getType());

    return index;
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * @param pStmt/* w  w  w .j av a  2s.co m*/
 * @param type
 * @param data
 * @throws SQLException 
 */
public static void setData(final PreparedStatement pStmt, final int type, final int colInx, final Object data)
        throws SQLException {
    if (data == null) {
        pStmt.setObject(colInx, null);
        return;
    }

    boolean isStr = data instanceof String;
    switch (type) {
    case java.sql.Types.TINYINT:
    case java.sql.Types.SMALLINT:
    case java.sql.Types.INTEGER:
        if (isStr) {
            pStmt.setString(colInx, (String) data);
        } else {
            pStmt.setInt(colInx, (Integer) data);
        }
        break;

    case java.sql.Types.FLOAT:
        if (isStr) {
            pStmt.setString(colInx, (String) data);
        } else {
            pStmt.setFloat(colInx, (Float) data);
        }
        break;

    case java.sql.Types.VARCHAR:
    case java.sql.Types.CHAR:
    case java.sql.Types.LONGVARCHAR:
    case java.sql.Types.LONGNVARCHAR:
    case java.sql.Types.NCHAR:
        if (isStr) {
            pStmt.setString(colInx, (String) data);
        } else {
            pStmt.setString(colInx, (String) data);
        }
        break;

    case java.sql.Types.REAL:
    case java.sql.Types.DOUBLE:
        if (isStr) {
            pStmt.setString(colInx, (String) data);
        } else {
            pStmt.setDouble(colInx, (Double) data);
        }
        break;

    case java.sql.Types.DATE:
        if (isStr) {
            pStmt.setString(colInx, (String) data);
        } else {
            pStmt.setDate(colInx, (java.sql.Date) data);
        }
        break;

    case java.sql.Types.TIMESTAMP:
        if (isStr) {
            pStmt.setString(colInx, (String) data);
        } else {
            pStmt.setTimestamp(colInx, (Timestamp) data);
        }
        break;

    case java.sql.Types.BOOLEAN:
        if (isStr) {
            String val = (String) data;
            pStmt.setBoolean(colInx, !val.equalsIgnoreCase("true"));
        } else {
            pStmt.setBoolean(colInx, (Boolean) data);
        }
        break;

    case java.sql.Types.BIT:
        if (data instanceof Boolean) {
            pStmt.setBoolean(colInx, (Boolean) data);
        } else {
            pStmt.setBoolean(colInx, !(((Integer) data) == 0));
        }
        break;

    default:
        throw new RuntimeException(String.format("Missing case for SQL Type %d for Column: %d Data[%s]", type,
                colInx, data.getClass().getSimpleName()));
    }
}