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:hoot.services.db.DbUtils.java

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

        switch (recordBatchType) {
        case INSERT:

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

            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentNodes node = (CurrentNodes) o;

                ps.setLong(1, node.getId());
                ps.setInt(2, node.getLatitude());
                ps.setInt(3, node.getLongitude());
                ps.setLong(4, node.getChangesetId());
                ps.setBoolean(5, node.getVisible());
                ps.setTimestamp(6, node.getTimestamp());
                ps.setLong(7, node.getTile());
                ps.setLong(8, node.getVersion());

                Map<String, String> tags = (Map<String, String>) node.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(9, hstoreStr, Types.OTHER);
                ps.addBatch();

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

                    }
                }

            }

            break;

        case UPDATE:

            sql = "update current_nodes_" + mapId + " set  latitude=?, "
                    + "longitude=?, changeset_id=?, visible=?, \"timestamp\"=?, tile=?, version=?, tags=? "
                    + "where id=?";
            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentNodes node = (CurrentNodes) o;

                ps.setInt(1, node.getLatitude());
                ps.setInt(2, node.getLongitude());
                ps.setLong(3, node.getChangesetId());
                ps.setBoolean(4, node.getVisible());
                ps.setTimestamp(5, node.getTimestamp());
                ps.setLong(6, node.getTile());
                ps.setLong(7, node.getVersion());

                Map<String, String> tags = (Map<String, String>) node.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(8, hstoreStr, Types.OTHER);

                ps.setLong(9, node.getId());

                ps.addBatch();

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

            break;

        case DELETE:

            sql = "delete from current_nodes_" + mapId + " where id=?";
            ps = conn.prepareStatement(sql);
            for (Object o : records) {
                CurrentNodes node = (CurrentNodes) o;

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

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

            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:egovframework.rte.bat.core.item.database.support.EgovMethodMapItemPreparedStatementSetter.java

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

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

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

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

From source file:org.kawanfw.test.api.client.InsertAndUpdatePrepStatementTest.java

/**
 * Do a 100 row insert inside a loop/*from   w ww  .j  a  v a  2 s .com*/
 * 
 * @param connection
 *            the AceQL Connection
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public void insertLoopPrepStatement(Connection connection, int numberToInsert) throws Exception {
    // We can now use our Remote JDBC Connection as a regular Connection!
    connection.setAutoCommit(false);

    // We will do all our remote insert in a SQL Transaction
    try {
        String sql = "insert into orderlog values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";

        // Create a new Prepared Statement
        PreparedStatement prepStatement = null;

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + numberToInsert + " orderlog...");

        SqlUtil sqlUtil = new SqlUtil(connection);

        for (int customerId = 1; customerId < numberToInsert + 1; customerId++) {
            int i = 1;
            long theTime = new java.util.Date().getTime();

            prepStatement = connection.prepareStatement(sql);

            prepStatement.setInt(i++, customerId);
            prepStatement.setInt(i++, customerId);
            prepStatement.setString(i++, "Item Description No " + customerId);
            prepStatement.setBigDecimal(i++, new BigDecimal(customerId));
            prepStatement.setDate(i++, new java.sql.Date(theTime));
            prepStatement.setTimestamp(i++, new Timestamp(theTime));

            prepStatement.setBytes(i++, null); // No Blob in this example.

            if (sqlUtil.isIngres() || sqlUtil.isPostgreSQL()) {
                prepStatement.setInt(i++, 0);
            } else {
                prepStatement.setBoolean(i++, false);
            }

            prepStatement.setInt(i++, customerId);

            prepStatement.executeUpdate();
            prepStatement.close();
        }

        // We do either everything in a single transaction or nothing
        connection.commit(); // Commit is propagated on Server
        MessageDisplayer.display("Remote Commit Done on AceQL Server!");
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(true);
    }

}

From source file:org.sakaiproject.chat2.model.impl.ChatManagerImpl.java

/**
 * Resets the passed context's default channel
 *
 *//*from  w ww  . ja va  2 s  . c  o  m*/
protected void resetPlacementDefaultChannel(String context, String placement) {
    Session session = null;
    Connection conn = null;
    PreparedStatement statement = null;

    String query = "update CHAT2_CHANNEL c set c.placementDefaultChannel=?, c.PLACEMENT_ID=? "
            + "WHERE c.context=? and c.PLACEMENT_ID=?";

    try {
        session = getSession();
        conn = session.connection();

        statement = conn.prepareStatement(query);
        statement.setBoolean(1, false);
        statement.setString(2, null);
        statement.setString(3, context);
        statement.setString(4, placement);
        statement.executeUpdate();
    } catch (Exception e) {
        logger.warn(e.getMessage());
    } finally {
        if (statement != null) {
            //ensure the statement is closed
            try {
                statement.close();
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug(e);
                }
            }
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ex) {
            logger.warn(ex.getMessage());
        }
    }
}

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

private void updateList(FxSelectListEdit list) throws FxApplicationException {
    if (!list.changes())
        return;//from  w w w  .  java  2s .  co  m
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.SelectListEditor);
    checkValidListParameters(list);
    //        System.out.println("Updating list " + list.getLabel());
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        //                                                                    1      2                   3
        ps = con.prepareStatement(
                "UPDATE " + TBL_STRUCT_SELECTLIST + " SET PARENTID=?,NAME=?,ALLOW_ITEM_CREATE=?," +
                //               4              5       6               7             8          9
                        "ACL_CREATE_ITEM=?,ACL_ITEM_NEW=?,BCSEP=?,SAMELVLSELECT=?,SORTENTRIES=? WHERE ID=?");
        if (list.hasParentList())
            ps.setLong(1, list.getParentList().getId());
        else
            ps.setNull(1, java.sql.Types.INTEGER);
        ps.setString(2, list.getName().trim());
        ps.setBoolean(3, list.isAllowDynamicItemCreation());
        ps.setLong(4, list.getCreateItemACL().getId());
        ps.setLong(5, list.getNewItemACL().getId());
        ps.setString(6, list.getBreadcrumbSeparator());
        ps.setBoolean(7, list.isOnlySameLevelSelect());
        ps.setBoolean(8, list.isSortEntries());
        ps.setLong(9, list.getId());
        ps.executeUpdate();
        Database.storeFxString(new FxString[] { list.getLabel(), list.getDescription() }, con,
                TBL_STRUCT_SELECTLIST, new String[] { "LABEL", "DESCRIPTION" }, "ID", list.getId());
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(TypeEngineBean.class, con, ps);
    }

}

From source file:net.duckling.ddl.service.resource.dao.ResourceDAOImpl.java

@Override
public void update(final List<Resource> res) {
    getJdbcTemplate().batchUpdate(SQL_UPDATE + BY_IDTIDTYPE, new BatchPreparedStatementSetter() {

        @Override/* w  w w . j a  va2  s  .c  o  m*/
        public void setValues(PreparedStatement ps, int index) throws SQLException {
            Resource r = res.get(index);
            int i = 0;
            ps.setString(++i, r.getTitle());
            ps.setString(++i, r.getLastEditor());
            ps.setString(++i, r.getLastEditorName());
            ps.setTimestamp(++i, new Timestamp(r.getLastEditTime().getTime()));
            ps.setInt(++i, r.getLastVersion());
            ps.setString(++i, r.getFileType());
            ps.setInt(++i, r.getBid());
            ps.setString(++i, r.getStatus());
            ps.setLong(++i, r.getSize());
            ps.setInt(++i, r.getRid());
            ps.setInt(++i, r.getTid());
            ps.setString(++i, r.getItemType());
            ps.setBoolean(i++, r.isShared());
        }

        @Override
        public int getBatchSize() {
            return res.size();
        }

    });
}

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

private long createList(FxSelectListEdit list) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.SelectListEditor);
    checkValidListParameters(list);/*from w  w w .ja  v a 2  s  . com*/
    long newId = seq.getId(FxSystemSequencer.SELECTLIST);
    list._synchronizeId(newId);
    //        System.out.println("Creating list " + list.getLabel() + " new id is " + newId);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        //                                                            1  2        3    4
        ps = con.prepareStatement(
                "INSERT INTO " + TBL_STRUCT_SELECTLIST + "(ID,PARENTID,NAME,ALLOW_ITEM_CREATE," +
                //5              6            7            8     9             10
                        "ACL_CREATE_ITEM,ACL_ITEM_NEW,DEFAULT_ITEM,BCSEP,SAMELVLSELECT,SORTENTRIES)VALUES(?,?,?,?,?,?,?,?,?,?)");
        ps.setLong(1, newId);
        if (list.hasParentList())
            ps.setLong(2, list.getParentList().getId());
        else
            ps.setNull(2, java.sql.Types.INTEGER);
        ps.setString(3, list.getName().trim());
        ps.setBoolean(4, list.isAllowDynamicItemCreation());
        ps.setLong(5, list.getCreateItemACL().getId());
        ps.setLong(6, list.getNewItemACL().getId());
        ps.setNull(7, java.sql.Types.INTEGER);
        ps.setString(8, list.getBreadcrumbSeparator());
        ps.setBoolean(9, list.isOnlySameLevelSelect());
        ps.setBoolean(10, list.isSortEntries());
        ps.executeUpdate();
        Database.storeFxString(new FxString[] { list.getLabel(), list.getDescription() }, con,
                TBL_STRUCT_SELECTLIST, new String[] { "LABEL", "DESCRIPTION" }, "ID", newId);
        return newId;
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(TypeEngineBean.class, con, ps);
    }
}

From source file:info.raack.appliancelabeler.data.JDBCDatabase.java

public void storeUserOnOffLabels(final List<ApplianceStateTransition> detectedStateTransitions) {

    for (final ApplianceStateTransition transition : detectedStateTransitions) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(insertApplianceStateTransition,
                        new String[] { "id" });

                ps.setInt(1, transition.getUserAppliance().getId());
                if (transition.getDetectionAlgorithmId() > 0) {
                    ps.setInt(2, transition.getDetectionAlgorithmId());
                } else {
                    ps.setNull(2, Types.INTEGER);
                }/*  www .  j  a v  a2 s.c  o  m*/
                ps.setLong(3, transition.getTime());
                ps.setBoolean(4, transition.isOn());
                return ps;
            }
        }, keyHolder);

        transition.setId(keyHolder.getKey().intValue());
    }
}

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

private void updateTerminatorTransaction(TransactionContext transactionContext, TerminatorArchive holder) {
    Connection connection = null;
    PreparedStatement stmt = null;
    try {/*  w  ww.j ava2s  .c  o  m*/
        connection = this.getConnection();

        StringBuilder ber = new StringBuilder();
        ber.append("update tcc_terminator set ");
        ber.append("prepared = ?, committed = ?, rolledback = ?, cleanup = ? ");
        ber.append("where application = ? and endpoint = ? and global_tx_id = ? ");
        ber.append("  and to_application = ? and to_endpoint = ?");
        stmt = connection.prepareStatement(ber.toString());

        XidImpl globalXid = transactionContext.getGlobalXid();
        RemoteTerminator terminator = holder.terminator;
        TerminalKey terminalKey = terminator.getTerminalKey();

        stmt.setBoolean(1, holder.prepared);
        stmt.setBoolean(2, holder.committed);
        stmt.setBoolean(3, holder.rolledback);
        stmt.setBoolean(4, holder.cleanup);
        stmt.setString(5, this.instanceKey.getApplication());
        stmt.setString(6, this.instanceKey.getEndpoint());
        stmt.setString(7, ByteUtils.byteArrayToString(globalXid.getGlobalTransactionId()));
        stmt.setString(8, terminalKey.getApplication());
        stmt.setString(9, terminalKey.getEndpoint());

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