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.gbif.portal.dao.impl.jdbc.ResourceAccessPointDAOImpl.java

/**
 * @see org.gbif.portal.dao.ResourceAccessPointDAO#setSupportsDateLastModified(boolean, long)
 *///from www .  j ava 2s.  co m
public void setSupportsDateLastModified(final boolean supports, final long id) {
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn
                    .prepareStatement(ResourceAccessPointDAOImpl.UPDATE_SUPPORTS_DATE_LAST_MODIFIED_SQL);
            ps.setBoolean(1, supports);
            ps.setLong(2, id);
            return ps;
        }
    });
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method updates the variable "isActive" in the database. The variable
 * "isActive" is a column of the table "OutputDevices". With this method the
 * output devices can notify if they are active and like to get messages or
 * not./*w  w w .j a  va 2  s. com*/
 * 
 * @param classes
 *            class of the output device
 * @param name
 *            name of the output device
 * @param active
 *            true= is active and like to get messages false=is not active
 *            and does not listen to messages
 */
@GET
@Path("/isActive/{classes}/{name}/{isActive}")
public synchronized static String isActive(@PathParam("classes") String classes, @PathParam("name") String name,
        @PathParam("isActive") String active) {
    createDBConnection();
    String ok = "ok";
    PreparedStatement st;
    try {
        boolean isActive = false;

        if (active.equals("t")) {
            isActive = true;
        }
        st = conn.prepareStatement("update \"OutputDevices\" set enabled=? where \"class\"=? and \"topic\"=?;");
        st.setBoolean(1, isActive);
        st.setString(2, classes);
        st.setString(3, name);
        st.execute();
        if (st.getUpdateCount() != 1) {
            ok = "class or topic not found";
        } else {
            deviceActive.put(classes + "," + name, isActive);
        }
    } catch (SQLException e) {
        logger.error("SQL Exception in Method isActive", e);
    }
    closeDBConnection();
    return ok;
}

From source file:org.apache.lucene.store.jdbc.JdbcDirectory.java

public String[] list() throws IOException {
    return (String[]) jdbcTemplate.executeSelect(table.sqlSelectNames(),
            new JdbcTemplate.ExecuteSelectCallback() {
                public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                    ps.setBoolean(1, false);
                }/*from   ww w . j  a v  a2 s. c  om*/

                public Object execute(ResultSet rs) throws Exception {
                    ArrayList names = new ArrayList();
                    while (rs.next()) {
                        names.add(rs.getString(1));
                    }
                    return (String[]) names.toArray(new String[names.size()]);
                }
            });
}

From source file:com.softberries.klerk.dao.AddressDao.java

public void update(Address c, QueryRunner run, Connection conn) throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_UPDATE_ADDRESS);
    st.setString(1, c.getCountry());//from www.  j  a va  2s.  c  o m
    st.setString(2, c.getCity());
    st.setString(3, c.getStreet());
    st.setString(4, c.getPostCode());
    st.setString(5, c.getHouseNumber());
    st.setString(6, c.getFlatNumber());
    st.setString(7, c.getNotes());
    st.setBoolean(8, c.isMain());
    if (c.getPerson_id() == null && c.getCompany_id() == null) {
        throw new SQLException("Either Person or Company needs to be specified");
    }
    if (c.getPerson_id().longValue() != 0) {
        st.setLong(9, c.getPerson_id());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getCompany_id().longValue() != 0) {
        st.setLong(10, c.getCompany_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    st.setLong(11, c.getId());
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_UPDATE_ADDRESS);
    }
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/**
 * Prepare a statement for iteration given a query string, fetch size
 * and some args.//from   w w w .j  av a 2 s  .c o  m
 *
 * NB: the provided connection is not closed.
 *
 * @param c a Database connection
 * @param fetchSize hint to JDBC driver on number of results to cache
 * @param query a query string  (must not be null or empty)
 * @param args some args to insert into this query string (must not be null)
 * @return a prepared statement
 * @throws SQLException If unable to prepare a statement
 * @throws ArgumentNotValid If unable to handle type of one the args, or
 * the arguments are either null or an empty String.
 */
public static PreparedStatement prepareStatement(Connection c, int fetchSize, String query, Object... args)
        throws SQLException {
    ArgumentNotValid.checkNotNull(c, "Connection c");
    ArgumentNotValid.checkPositive(fetchSize, "int fetchSize");
    ArgumentNotValid.checkNotNullOrEmpty(query, "String query");
    ArgumentNotValid.checkNotNull(args, "Object... args");
    c.setAutoCommit(false);
    PreparedStatement s = c.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    s.setFetchSize(fetchSize);
    int i = 1;
    for (Object arg : args) {
        if (arg instanceof String) {
            s.setString(i, (String) arg);
        } else if (arg instanceof Integer) {
            s.setInt(i, (Integer) arg);
        } else if (arg instanceof Long) {
            s.setLong(i, (Long) arg);
        } else if (arg instanceof Boolean) {
            s.setBoolean(i, (Boolean) arg);
        } else if (arg instanceof Date) {
            s.setTimestamp(i, new Timestamp(((Date) arg).getTime()));
        } else {
            throw new ArgumentNotValid("Cannot handle type '" + arg.getClass().getName()
                    + "'. We can only handle string, " + "int, long, date or boolean args for query: " + query);
        }
        i++;
    }
    return s;
}

From source file:org.schedoscope.metascope.tasks.repository.jdbc.impl.FieldEntityJdbcRepository.java

@Override
public void save(Connection connection, FieldEntity fieldEntity) {
    String insertFieldSql = "insert into field_entity ("
            + JDBCUtil.getDatabaseColumnsForClass(FieldEntity.class) + ") values ("
            + JDBCUtil.getValuesCountForClass(FieldEntity.class) + ")";
    PreparedStatement stmt = null;
    try {/*  w w  w. java  2 s.c  o  m*/
        stmt = connection.prepareStatement(insertFieldSql);
        stmt.setString(1, fieldEntity.getFqdn());
        stmt.setString(2, fieldEntity.getName());
        stmt.setString(3, fieldEntity.getType());
        stmt.setString(4, fieldEntity.getDescription());
        stmt.setInt(5, fieldEntity.getFieldOrder());
        stmt.setBoolean(6, fieldEntity.isParameterField());
        stmt.setString(7, fieldEntity.getFqdn());
        stmt.execute();
    } catch (SQLException e) {
        LOG.error("Could not save field", e);
    } finally {
        DbUtils.closeQuietly(stmt);
    }
}

From source file:org.schedoscope.metascope.tasks.repository.jdbc.impl.FieldEntityJdbcRepository.java

@Override
public void update(Connection connection, FieldEntity fieldEntity) {
    String updateFieldSql = "update field_entity set " + JDBCUtil.getSetExpressionForClass(FieldEntity.class)
            + " where " + FieldEntity.FQDN + " = ? and " + FieldEntity.NAME + " = ?";
    PreparedStatement stmt = null;
    try {// w w  w . j  a v  a2  s.  c om
        stmt = connection.prepareStatement(updateFieldSql);
        stmt.setString(1, fieldEntity.getFqdn());
        stmt.setString(2, fieldEntity.getName());
        stmt.setString(3, fieldEntity.getType());
        stmt.setString(4, fieldEntity.getDescription());
        stmt.setInt(5, fieldEntity.getFieldOrder());
        stmt.setBoolean(6, fieldEntity.isParameterField());
        stmt.setString(7, fieldEntity.getFqdn());
        stmt.setString(8, fieldEntity.getFqdn());
        stmt.setString(9, fieldEntity.getName());
        stmt.execute();
    } catch (SQLException e) {
        LOG.error("Could not update field", e);
    } finally {
        DbUtils.closeQuietly(stmt);
    }
}

From source file:com.flexive.core.storage.MySQL.MySQLSequencerStorage.java

/**
 * {@inheritDoc}//from w ww . j  a  va  2  s .co m
 */
@Override
public void createSequencer(String name, boolean allowRollover, long startNumber)
        throws FxApplicationException {
    if (StringUtils.isEmpty(name) || name.toUpperCase().trim().startsWith("SYS_"))
        throw new FxCreateException(LOG, "ex.sequencer.create.invalid.name", name);
    name = name.toUpperCase().trim();
    if (sequencerExists(name))
        throw new FxCreateException(LOG, "ex.sequencer.create.invalid.name", name);

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();

        ps = con.prepareStatement(SQL_CREATE);
        ps.setLong(1, startNumber);
        ps.setString(2, name);
        ps.setBoolean(3, allowRollover);
        ps.executeUpdate();
        if (ps.getUpdateCount() == 0)
            throw new FxCreateException(LOG, "ex.sequencer.create.failed", name);
    } catch (SQLException exc) {
        throw new FxCreateException(LOG, exc, "ex.sequencer.create.failed", name);
    } finally {
        Database.closeObjects(MySQLSequencerStorage.class, con, ps);
    }
}

From source file:com.softberries.klerk.dao.AddressDao.java

public void create(Address c, QueryRunner run, Connection conn, ResultSet generatedKeys) throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_INSERT_ADDRESS, Statement.RETURN_GENERATED_KEYS);
    st.setString(1, c.getCountry());//www. j  a va 2 s  .c om
    st.setString(2, c.getCity());
    st.setString(3, c.getStreet());
    st.setString(4, c.getPostCode());
    st.setString(5, c.getHouseNumber());
    st.setString(6, c.getFlatNumber());
    st.setString(7, c.getNotes());
    st.setBoolean(8, c.isMain());
    if (c.getPerson_id().longValue() == 0 && c.getCompany_id().longValue() == 0) {
        throw new SQLException("For Address either Person or Company needs to be specified");
    }
    if (c.getPerson_id().longValue() != 0) {
        st.setLong(9, c.getPerson_id());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getCompany_id().longValue() != 0) {
        st.setLong(10, c.getCompany_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_INSERT_ADDRESS);
    }
    generatedKeys = st.getGeneratedKeys();
    if (generatedKeys.next()) {
        c.setId(generatedKeys.getLong(1));
    } else {
        throw new SQLException("Creating address failed, no generated key obtained.");
    }
}

From source file:mitll.xdata.dataset.kiva.ingest.KivaIngest.java

public static int executePreparedStatement(PreparedStatement statement, List<String> types, List<String> values)
        throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    try {//from ww w  .ja  va2s .  c om
        for (int i = 0; i < types.size(); i++) {
            String type = TYPE_TO_DB.get(types.get(i).toUpperCase());
            String value = values.get(i);
            if (value != null && value.trim().length() == 0) {
                value = null;
            }
            if (type.equalsIgnoreCase("INT")) {
                if (value == null) {
                    statement.setNull(i + 1, java.sql.Types.INTEGER);
                } else {
                    statement.setInt(i + 1, Integer.parseInt(value, 10));
                }
            } else if (type.equalsIgnoreCase("DOUBLE")) {
                if (value == null) {
                    statement.setNull(i + 1, java.sql.Types.DOUBLE);
                } else {
                    statement.setDouble(i + 1, Double.parseDouble(value));
                }
            } else if (type.equalsIgnoreCase("BOOLEAN")) {
                if (value == null) {
                    statement.setNull(i + 1, java.sql.Types.BOOLEAN);
                } else {
                    statement.setBoolean(i + 1, Boolean.parseBoolean(value));
                }
            } else if (type.equalsIgnoreCase("VARCHAR")) {
                statement.setString(i + 1, value);
            } else if (type.equalsIgnoreCase("TIMESTAMP")) {
                if (value == null) {
                    statement.setNull(i + 1, java.sql.Types.TIMESTAMP);
                } else {
                    statement.setTimestamp(i + 1, new Timestamp(sdf.parse(value).getTime()));
                }
            }
        }
    } catch (Throwable e) {
        System.out.println("types = " + types);
        System.out.println("values = " + values);
        System.out.println("types.size() = " + types.size());
        System.out.println("values.size() = " + values.size());
        e.printStackTrace();
        System.out.println(e.getMessage());
        throw new Exception(e);
    }
    return statement.executeUpdate();
}