Example usage for java.sql PreparedStatement setNull

List of usage examples for java.sql PreparedStatement setNull

Introduction

In this page you can find the example usage for java.sql PreparedStatement setNull.

Prototype

void setNull(int parameterIndex, int sqlType) throws SQLException;

Source Link

Document

Sets the designated parameter to SQL NULL.

Usage

From source file:nl.nn.adapterframework.statistics.jdbc.StatisticsKeeperStore.java

private void applyParam(PreparedStatement stmt, int pos, long value) throws SQLException {
    if (trace && log.isDebugEnabled())
        log.debug("pos [" + pos + "] set long param [" + value + "]");
    if (value == Long.MAX_VALUE) {
        stmt.setNull(pos, Types.NUMERIC);
    } else {/*from w w w . j a  va  2s.co  m*/
        stmt.setLong(pos, value);
    }
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.BookManagerImpl.java

@Override
@Transactional(readOnly = false)/*ww  w  . j a v  a 2 s  .  c o  m*/
public void createBook(Book book) {
    validate(book);
    if (book.getId() != null) {
        throw new IllegalArgumentException("book id is already set");
    }

    KeyHolder keyHolder = new GeneratedKeyHolder();
    int updated = jdbcTemplate.update((Connection connection) -> {
        PreparedStatement ps = connection.prepareStatement(
                "INSERT INTO BOOK (name,isbn,published,author_id) VALUES (?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, book.getName());
        ps.setString(2, book.getIsbn());
        Date date = Date.valueOf(book.getPublished());
        ps.setDate(3, date);
        if (book.getAuthorId() == null) {
            ps.setNull(4, Types.BIGINT);
        } else {
            ps.setLong(4, book.getAuthorId());
        }
        return ps;
    }, keyHolder);

    book.setId(keyHolder.getKey().longValue());

    DBUtils.checkUpdatesCount(updated, book, true);
}

From source file:hermes.store.schema.DefaultJDBCAdapter.java

private PreparedStatement createPreparedStatement(Connection connection, String sql, Object[] params)
        throws SQLException {
    final PreparedStatement stmt = connection.prepareStatement(sql);

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                stmt.setObject(i + 1, params[i]);
            } else {
                stmt.setNull(i + 1, Types.OTHER);
            }//from   w  w  w .jav a2 s  .c om
        }
    }

    return stmt;
}

From source file:net.solarnetwork.node.dao.jdbc.power.JdbcPowerDatumDao.java

@Override
protected void setStoreStatementValues(PowerDatum datum, PreparedStatement ps) throws SQLException {
    int col = 1;/*from ww w. j a v  a  2  s . c o  m*/
    ps.setTimestamp(col++, new java.sql.Timestamp(
            datum.getCreated() == null ? System.currentTimeMillis() : datum.getCreated().getTime()));
    ps.setString(col++, datum.getSourceId() == null ? "" : datum.getSourceId());
    if (datum.getLocationId() == null) {
        ps.setNull(col++, Types.BIGINT);
    } else {
        ps.setLong(col++, datum.getLocationId());
    }
    if (datum.getWatts() == null) {
        ps.setNull(col++, Types.INTEGER);
    } else {
        ps.setInt(col++, datum.getWatts());
    }
    if (datum.getBatteryVolts() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getBatteryVolts());
    }
    if (datum.getBatteryAmpHours() == null) {
        ps.setNull(col++, Types.DOUBLE);
    } else {
        ps.setDouble(col++, datum.getBatteryAmpHours());
    }
    if (datum.getDcOutputVolts() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getDcOutputVolts());
    }
    if (datum.getDcOutputAmps() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getDcOutputAmps());
    }
    if (datum.getAcOutputVolts() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getAcOutputVolts());
    }
    if (datum.getAcOutputAmps() == null) {
        ps.setNull(col++, Types.FLOAT);
    } else {
        ps.setFloat(col++, datum.getAcOutputAmps());
    }
    if (datum.getWattHourReading() == null) {
        ps.setNull(col++, Types.BIGINT);
    } else {
        ps.setLong(col++, datum.getWattHourReading());
    }
    if (datum.getAmpHourReading() == null) {
        ps.setNull(col++, Types.DOUBLE);
    } else {
        ps.setDouble(col++, datum.getAmpHourReading());
    }
}

From source file:nl.nn.adapterframework.statistics.jdbc.StatisticsKeeperStore.java

private void applyParam(PreparedStatement stmt, int pos, double value) throws SQLException {
    if (Double.isNaN(value)) {
        if (trace && log.isDebugEnabled())
            log.debug("pos [" + pos + "] set double param [" + value + "], setting to NULL");
        stmt.setNull(pos, Types.DOUBLE);
    } else {//from w w w . ja  v  a2s . c  o m
        if (trace && log.isDebugEnabled())
            log.debug("pos [" + pos + "] set double param [" + value + "]");
        stmt.setDouble(pos, value);
    }
}

From source file:com.jaspersoft.jasperserver.util.JasperJdbcContainer.java

/**
 * Given a array of jdbc parameters and a PreparedStatment loops through the parameter array
 * and populates the PreparedStatement/*from w  w w .  java2s  .c  om*/
 * @param params jdbc parameters extracted from a CachedRowSet 
 * @param pstmt  the PreparedStatment to populate
 * @throws SQLException
 */
private void insertParameters(Object[] params, PreparedStatement pstmt) throws SQLException {

    Object[] param = null;

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

        if (params[i] instanceof Object[]) {
            param = (Object[]) params[i];
            if (param.length == 2) {
                if (param[0] == null) {
                    pstmt.setNull(i + 1, ((Integer) param[1]).intValue());
                    continue;
                }

                if (param[0] instanceof java.sql.Date || param[0] instanceof java.sql.Time
                        || param[0] instanceof java.sql.Timestamp) {
                    if (param[1] instanceof java.util.Calendar) {
                        pstmt.setDate(i + 1, (java.sql.Date) param[0], (java.util.Calendar) param[1]);
                        continue;
                    } else {
                        throw new SQLException("Unknown Parameter, expected java.util.Calendar");
                    }
                }

                if (param[0] instanceof Reader) {
                    pstmt.setCharacterStream(i + 1, (Reader) param[0], ((Integer) param[1]).intValue());
                    continue;
                }

                /*
                 * What's left should be setObject(int, Object, scale)
                 */
                if (param[1] instanceof Integer) {
                    pstmt.setObject(i + 1, param[0], ((Integer) param[1]).intValue());
                    continue;
                }

            } else if (param.length == 3) {

                if (param[0] == null) {
                    pstmt.setNull(i + 1, ((Integer) param[1]).intValue(), (String) param[2]);
                    continue;
                }

                // need to find and fix inputstreams
                if (param[0] instanceof java.io.InputStream) {
                    //logger.fine("Found parameter of type input stream");
                } //inputstream if

                /*
                 * no point at looking at the first element now; what's left
                 * must be the setObject() cases.
                 */
                if (param[1] instanceof Integer && param[2] instanceof Integer) {
                    pstmt.setObject(i + 1, param[0], ((Integer) param[1]).intValue(),
                            ((Integer) param[2]).intValue());
                    continue;
                }
                throw new SQLException("Unexpected Parameter");

            } else {
                // common case - this catches all SQL92 types
                pstmt.setObject(i + 1, params[i]);
                continue;
            }
        } else {
            // Try to get all the params to be set here
            pstmt.setObject(i + 1, params[i]);
            //logger.finest("Param" + i+ ": " + params[i]);
        }
    } //for
      //logger.exiting(getClass().getName(), "insertParameters");
}

From source file:mx.edu.um.escuela.dao.MaestroDaoJdbc.java

@Override
public Maestro crea(final Maestro maestro) {
    log.debug("Creando al maestro {}", maestro);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override//from   w  w w. j  av  a2 s  . c  o  m
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(CREAR_MAESTRO, new String[] { "id" });
            ps.setString(1, maestro.getNomina());
            ps.setString(2, maestro.getNombre());
            ps.setString(3, maestro.getApellido());
            if (maestro.getFechaNacimiento() != null) {
                ps.setDate(4, new java.sql.Date(maestro.getFechaNacimiento().getTime()));
            } else {
                ps.setNull(4, Types.DATE);
            }
            ps.setBoolean(5, maestro.getEsHombre());
            if (maestro.getCorreo() != null) {
                ps.setString(6, maestro.getCorreo());
            } else {
                ps.setNull(6, Types.VARCHAR);
            }
            return ps;
        }
    }, keyHolder);
    maestro.setId(keyHolder.getKey().longValue());

    maestros.add(maestro);
    return maestro;
}

From source file:com.opengamma.masterdb.security.hibernate.EnumUserType.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Override/*from www. ja  v a 2s  .  c o m*/
public void nullSafeSet(PreparedStatement stmt, Object value, int index)
        throws HibernateException, SQLException {
    if (value == null) {
        // NOTE kirk 2010-06-11 -- This has to remain deprecated due to a bug in Hibernate 3.5.2
        // where they deprecated the constants there (e.g. Hibernate.STRING) but didn't put in
        // the StringType.INSTNANCE you're supposed to use instead.
        // When we upgrade to a new hibernate which doesn't have this bug, we need to change.
        stmt.setNull(index, Hibernate.STRING.sqlType());
    } else {
        stmt.setString(index, enumToString((E) value));
    }
}

From source file:org.entando.entando.aps.system.services.guifragment.GuiFragmentDAO.java

protected void insertGuiFragment(GuiFragment guiFragment, Connection conn) {
    PreparedStatement stat = null;
    try {// www. j a  v a2  s . c  o m
        stat = conn.prepareStatement(ADD_GUIFRAGMENT);
        int index = 1;
        stat.setString(index++, guiFragment.getCode());
        if (StringUtils.isNotBlank(guiFragment.getWidgetTypeCode())) {
            stat.setString(index++, guiFragment.getWidgetTypeCode());
        } else {
            stat.setNull(index++, Types.VARCHAR);
        }
        if (StringUtils.isNotBlank(guiFragment.getPluginCode())) {
            stat.setString(index++, guiFragment.getPluginCode());
        } else {
            stat.setNull(index++, Types.VARCHAR);
        }
        stat.setString(index++, guiFragment.getGui());
        stat.setInt(index++, 0);
        stat.executeUpdate();
    } catch (Throwable t) {
        _logger.error("Error on insert guiFragment", t);
        throw new RuntimeException("Error on insert guiFragment", t);
    } finally {
        this.closeDaoResources(null, stat);
    }
}

From source file:lineage2.gameserver.cache.CrestCache.java

/**
 * Method removePledgeCrest./*from w  w  w .  j  a  va 2s . c  om*/
 * @param pledgeId int
 */
public void removePledgeCrest(int pledgeId) {
    writeLock.lock();
    try {
        _pledgeCrest.remove(_pledgeCrestId.remove(pledgeId));
    } finally {
        writeLock.unlock();
    }
    Connection con = null;
    PreparedStatement statement = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement("UPDATE clan_data SET crest=? WHERE clan_id=?");
        statement.setNull(1, Types.VARBINARY);
        statement.setInt(2, pledgeId);
        statement.execute();
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        DbUtils.closeQuietly(con, statement);
    }
}