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:com.jagornet.dhcp.db.JdbcIaAddressDAO.java

public void update(final IaAddress iaAddr) {
    String updateQuery = "update iaaddress" + " set ipaddress=?," + " starttime=?," + " preferredendtime=?,"
            + " validendtime=?," + " state=?," + " identityassoc_id=?" + " where id=?";
    getJdbcTemplate().update(updateQuery, new PreparedStatementSetter() {
        @Override/*  ww  w  .jav a2s.  c  o m*/
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setBytes(1, iaAddr.getIpAddress().getAddress());
            Date start = iaAddr.getStartTime();
            if (start != null) {
                java.sql.Timestamp sts = new java.sql.Timestamp(start.getTime());
                ps.setTimestamp(2, sts, Util.GMT_CALENDAR);
            } else {
                ps.setNull(2, java.sql.Types.TIMESTAMP);
            }
            Date preferred = iaAddr.getPreferredEndTime();
            if (preferred != null) {
                java.sql.Timestamp pts = new java.sql.Timestamp(preferred.getTime());
                ps.setTimestamp(3, pts, Util.GMT_CALENDAR);
            } else {
                ps.setNull(3, java.sql.Types.TIMESTAMP);
            }
            Date valid = iaAddr.getValidEndTime();
            if (valid != null) {
                java.sql.Timestamp vts = new java.sql.Timestamp(valid.getTime());
                ps.setTimestamp(4, vts, Util.GMT_CALENDAR);
            } else {
                ps.setNull(4, java.sql.Types.TIMESTAMP);
            }
            ps.setByte(5, iaAddr.getState());
            ps.setLong(6, iaAddr.getIdentityAssocId());
            ps.setLong(7, iaAddr.getId());
        }
    });
}

From source file:net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.DataTypeBigDecimal.java

/**
 * When updating the database, insert the appropriate datatype into the
 * prepared statment at the given variable position.
 */// w  w w .j  a v  a 2  s .c  o m
public void setPreparedStatementValue(PreparedStatement pstmt, Object value, int position)
        throws java.sql.SQLException {
    if (value == null) {
        pstmt.setNull(position, _colDef.getSqlType());
    } else {
        pstmt.setBigDecimal(position, (BigDecimal) value);
    }
}

From source file:nl.tudelft.stocktrader.derby.DerbyOrderDAO.java

public void closeOrder(Order order) throws DAOException {
    if (logger.isDebugEnabled()) {
        logger.debug("OrderDAO.closeOrder(OrderDataModel)\nOrderID :" + order.getOrderID() + "\nOrderType :"
                + order.getOrderType() + "\nSymbol :" + order.getSymbol() + "\nQuantity :" + order.getQuantity()
                + "\nOrder Status :" + order.getOrderStatus() + "\nOrder Open Date :" + order.getOpenDate()
                + "\nCompletionDate :" + order.getCompletionDate());
    }//from   w w  w .  j a  v a  2  s .  com

    PreparedStatement closeOrderStat = null;
    try {
        closeOrderStat = sqlConnection.prepareStatement(SQL_CLOSE_ORDER);
        closeOrderStat.setString(1, StockTraderUtility.ORDER_STATUS_CLOSED);
        if (StockTraderUtility.ORDER_TYPE_SELL.equals(order.getOrderType())) {
            closeOrderStat.setNull(2, Types.INTEGER);
        } else {
            closeOrderStat.setInt(2, order.getHoldingId());
        }
        closeOrderStat.setBigDecimal(3, order.getPrice());
        closeOrderStat.setInt(4, order.getOrderID());
        closeOrderStat.executeUpdate();

    } catch (SQLException e) {
        throw new DAOException("", e);

    } finally {
        if (closeOrderStat != null) {
            try {
                closeOrderStat.close();
            } catch (Exception e) {
                logger.debug("", e);
            }
        }
    }
}

From source file:edu.ku.brc.specify.toycode.RegAdder.java

/**
 * @param trackItemId//from  w  ww. ja  v a2 s  .  c o m
 * @param value
 * @param pStmt
 */
private void doTrackUpdate(final int trackItemId, final String value, final PreparedStatement pStmt)
        throws SQLException {
    if (!StringUtils.contains(value, ".") && StringUtils.isNumeric(value) && value.length() < 10) {
        pStmt.setInt(1, Integer.parseInt(value));
        pStmt.setNull(2, java.sql.Types.VARCHAR);

    } else if (value.length() < STR_SIZE + 1) {
        pStmt.setNull(1, java.sql.Types.INTEGER);
        pStmt.setString(2, value);

    } else {
        String v = value.substring(0, STR_SIZE);
        System.err.println(
                "Error - On line " + lineNo + " Value[" + value + "] too big trunccating to[" + v + "]");

        pStmt.setNull(1, java.sql.Types.INTEGER);
        pStmt.setString(2, v);
    }
    pStmt.setInt(3, trackItemId);

    int rv = pStmt.executeUpdate();
    if (rv != 1) {
        throw new RuntimeException("Error insert trackitem for Id: " + trackItemId);
    }
}

From source file:car_counter.storage.sqlite.SqliteStorage.java

@Override
public void store(Path destinationFile, Collection<DetectedVehicle> detectedVehicles) {
    try {/*w  w  w  . ja  v a2s  .  com*/
        PreparedStatement statement = connection.prepareStatement("insert into detected_vehicles "
                + "(timestamp, initial_location, end_location, speed, colour, video_file) values "
                + "(?, ?, ?, ?, ?, ?)");

        for (DetectedVehicle detectedVehicle : detectedVehicles) {
            statement.setLong(1, detectedVehicle.getDateTime().getMillis());
            statement.setLong(2, detectedVehicle.getInitialLocation().ordinal());
            statement.setLong(3, detectedVehicle.getEndLocation().ordinal());

            if (detectedVehicle.getSpeed() == null) {
                statement.setNull(4, Types.NULL);
            } else {
                statement.setFloat(4, detectedVehicle.getSpeed());
            }

            statement.setString(5, null);
            statement.setString(6, destinationFile.getFileName().toString());

            statement.executeUpdate();
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Error inserting records", e);
    }
}

From source file:com.nabla.wapp.server.auth.UserManager.java

public boolean updateUserDefinition(final Integer objectId, final Integer userId, final SelectionDelta delta)
        throws SQLException {
    Assert.argumentNotNull(userId);//from   www  . ja v  a  2 s .co m
    Assert.argumentNotNull(delta);

    final LockTableGuard lock = new LockTableGuard(conn, LOCK_USER_TABLES);
    try {
        final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn);
        try {
            if (delta.isRemovals()) {
                if (objectId == null)
                    Database.executeUpdate(conn,
                            "DELETE FROM user_definition WHERE object_id IS NULL AND user_id=? AND role_id IN (?);",
                            userId, delta.getRemovals());
                else
                    Database.executeUpdate(conn,
                            "DELETE FROM user_definition WHERE object_id=? AND user_id=? AND role_id IN (?);",
                            objectId, userId, delta.getRemovals());
            }
            if (delta.isAdditions()) {
                final PreparedStatement stmt = conn.prepareStatement(
                        "INSERT INTO user_definition (object_id, user_id, role_id) VALUES(?,?,?);");
                try {
                    stmt.clearBatch();
                    if (objectId == null)
                        stmt.setNull(1, Types.BIGINT);
                    else
                        stmt.setInt(1, objectId);
                    stmt.setInt(2, userId);
                    for (final Integer childId : delta.getAdditions()) {
                        stmt.setInt(3, childId);
                        stmt.addBatch();
                    }
                    if (!Database.isBatchCompleted(stmt.executeBatch()))
                        return false;
                } finally {
                    stmt.close();
                }
            }
            return guard.setSuccess(updateUserRoleTable());
        } finally {
            guard.close();
        }
    } finally {
        lock.close();
    }
}

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

protected void bindInsertOrUpdateParameters(PreparedStatement stmt, String constructId, String chemical,
        String kind, Integer index) throws SQLException {
    stmt.setString(DB_FIELD.CONSTRUCT_ID.getInsertUpdateOffset(), constructId);
    stmt.setString(DB_FIELD.CHEMICAL.getInsertUpdateOffset(), chemical);
    stmt.setString(DB_FIELD.KIND.getInsertUpdateOffset(), kind);
    if (index != null) {
        stmt.setInt(DB_FIELD.INDEX.getInsertUpdateOffset(), index);
    } else {/*ww  w  .  j  a  v  a 2  s.co  m*/
        stmt.setNull(DB_FIELD.INDEX.getInsertUpdateOffset(), Types.INTEGER);
    }
}

From source file:com.google.flightmap.parsing.faa.afd.AfdCommParser.java

private void addAirportCommToDb(final String iata, final String identifier, final String frequency,
        final String remarks) throws SQLException {
    final PreparedStatement addAirportCommStmt = dbConn.prepareStatement(
            "INSERT INTO airport_comm (airport_id, identifier, frequency, remarks) " + "VALUES (?, ?, ?, ?)");
    final int airportId = getAirportId(iata);
    if (airportId != -1) {
        addAirportCommStmt.setInt(1, getAirportId(iata));
        addAirportCommStmt.setString(2, identifier);
        addAirportCommStmt.setString(3, frequency);
        if (remarks != null) {
            addAirportCommStmt.setString(4, remarks);
        } else {//  w w  w  .  ja va 2 s .c  o  m
            addAirportCommStmt.setNull(4, Types.VARCHAR);
        }
        addAirportCommStmt.executeUpdate();
    }
}

From source file:com.nabla.wapp.server.auth.UserManager.java

public boolean updateUserRoleTable() throws SQLException {
    final Map<Integer, Map<Integer, Set<Integer>>> userRoles = loadUserRoles();
    Database.executeUpdate(conn, "DELETE FROM user_role;");
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO user_role (object_id, user_id, role_id) VALUES(?,?,?);");
    try {//from www  . ja  v  a 2  s  . c om
        stmt.clearBatch();
        for (Map.Entry<Integer, Map<Integer, Set<Integer>>> e : userRoles.entrySet()) {
            if (e.getKey() == null)
                stmt.setNull(1, Types.BIGINT);
            else
                stmt.setInt(1, e.getKey());
            for (Map.Entry<Integer, Set<Integer>> ee : e.getValue().entrySet()) {
                stmt.setInt(2, ee.getKey());
                for (Integer roleId : ee.getValue()) {
                    stmt.setInt(3, roleId);
                    stmt.addBatch();
                }
            }
        }
        return Database.isBatchCompleted(stmt.executeBatch());
    } finally {
        stmt.close();
    }
}

From source file:com.nabla.wapp.report.server.ReportManager.java

public int addReport(final Connection conn, final String reportName, @Nullable final String internalName,
        final InputStream design, final InputStream in) throws SQLException, DispatchException {
    // load and scan report design
    if (log.isDebugEnabled())
        log.debug("scanning report " + reportName);
    ReportDesign report;/*  ww  w.jav  a  2  s  .  co  m*/
    try {
        report = new Persister().read(ReportDesign.class, design);
    } catch (Exception e) {
        if (log.isErrorEnabled())
            log.error("fail to load report design", e);
        throw new InternalErrorException(Util.formatInternalErrorDescription(e));
    }
    // add report record
    final Integer roleId = getRole(conn, report.getRole());
    if (roleId == null) {
        if (log.isErrorEnabled())
            log.error("invalid role '" + report.getRole() + "' defined for report '" + reportName + "'");
        throw new DispatchException(ReportErrors.REPORT_DESIGN_INVALID_ROLE);
    }
    final String category = report.getCategory();
    if (!reportCategoryValidator.isValid(category)) {
        if (log.isErrorEnabled())
            log.error("invalid category '" + category + "' defined for report ' " + reportName + "'");
        throw new DispatchException(ReportErrors.REPORT_DESIGN_INVALID_CATEGORY);
    }
    final PreparedStatement stmt = conn.prepareStatement(
            "INSERT INTO report (name,internal_name,category,role_id,content) VALUES(?,?,?,?,?);",
            Statement.RETURN_GENERATED_KEYS);
    try {
        stmt.setString(1, report.getTitle());
        if (internalName != null)
            stmt.setString(2, internalName);
        else
            stmt.setNull(2, Types.VARCHAR);
        if (category != null)
            stmt.setString(3, category);
        else
            stmt.setNull(3, Types.VARCHAR);
        stmt.setInt(4, roleId);
        stmt.setBinaryStream(5, in);
        if (log.isDebugEnabled())
            log.debug("uploading report " + reportName);
        if (stmt.executeUpdate() != 1) {
            if (log.isErrorEnabled())
                log.error("failed to add internal report '" + reportName + "'");
            throw new InternalErrorException();
        }
        final ResultSet rsKey = stmt.getGeneratedKeys();
        try {
            rsKey.next();
            return rsKey.getInt(1);
        } finally {
            rsKey.close();
        }
    } finally {
        stmt.close();
    }
}