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.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void update(final Ligplaats origineel, final Ligplaats mutation) throws DAOException {
    try {/*from  w ww .  j av a 2 s .com*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement("update bag_ligplaats set"
                                + " aanduiding_record_inactief = ?," + " aanduiding_record_correctie = ?,"
                                + " officieel = ?," + " ligplaats_status = ?," + " ligplaats_geometrie = ?,"
                                + " einddatum_tijdvak_geldigheid = ?," + " in_onderzoek = ?,"
                                + " bron_documentdatum = ?," + " bron_documentnummer = ?,"
                                + " bag_nummeraanduiding_id = ?" + " where bag_ligplaats_id = ?"
                                + " and aanduiding_record_correctie = ?"
                                + " and begindatum_tijdvak_geldigheid = ?");
                        ps.setInt(1, mutation.getAanduidingRecordInactief().ordinal());
                        ps.setLong(2, mutation.getAanduidingRecordCorrectie());
                        ps.setInt(3, mutation.getOfficieel().ordinal());
                        ps.setInt(4, mutation.getLigplaatsStatus().ordinal());
                        ps.setString(5, mutation.getLigplaatsGeometrie());
                        if (mutation.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(6, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(6,
                                    new Timestamp(mutation.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(7, mutation.getInOnderzoek().ordinal());
                        ps.setDate(8, new Date(mutation.getDocumentdatum().getTime()));
                        ps.setString(9, mutation.getDocumentnummer());
                        ps.setLong(10, mutation.getHoofdAdres());
                        ps.setLong(11, origineel.getIdentificatie());
                        ps.setLong(12, origineel.getAanduidingRecordCorrectie());
                        ps.setTimestamp(13,
                                new Timestamp(origineel.getBegindatumTijdvakGeldigheid().getTime()));
                        return ps;
                    }
                });
                deleteNevenadressen(TypeAdresseerbaarObject.LIGPLAATS, origineel);
                insertNevenadressen(TypeAdresseerbaarObject.LIGPLAATS, mutation);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error updating ligplaats: " + origineel.getIdentificatie(), e);
    }
}

From source file:it.fub.jardin.server.DbUtils.java

/**
 * Put a Java Object in a PreparedStatement. Return the number of transferred
 * Objects.//ww  w  . j  av  a  2 s .com
 * 
 * @param ps
 *          The PreparedStatement to modify
 * @param i
 *          The index in which to put the Java Object
 * @param value
 *          The Object to put in the PreparedStatement
 * @return Number of transferred Objects (1 if all went OK, 0 otherwise). Tip:
 *         you can use this value to increment index pointer.
 * @throws SQLException
 */
private Integer putJavaObjectInPs(final PreparedStatement ps, final Integer i, final Object value)
        throws SQLException {

    // TODO Warning!
    if ((value != null) && (value.toString().length() > 0)) {
        ps.setObject(i, value);
    } else {
        ps.setNull(i, Types.NULL);
    }

    return 1;
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void update(final Standplaats origineel, final Standplaats mutation) throws DAOException {
    try {//from   www  .  j a  v  a2 s  .c  o m
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement("update bag_standplaats set"
                                + " aanduiding_record_inactief = ?," + " aanduiding_record_correctie = ?,"
                                + " officieel = ?," + " standplaats_status = ?," + " standplaats_geometrie = ?,"
                                + " einddatum_tijdvak_geldigheid = ?," + " in_onderzoek = ?,"
                                + " bron_documentdatum = ?," + " bron_documentnummer = ?,"
                                + " bag_nummeraanduiding_id = ?" + " where bag_standplaats_id = ?"
                                + " and aanduiding_record_correctie = ?"
                                + " and begindatum_tijdvak_geldigheid = ?");
                        ps.setInt(1, mutation.getAanduidingRecordInactief().ordinal());
                        ps.setLong(2, mutation.getAanduidingRecordCorrectie());
                        ps.setInt(3, mutation.getOfficieel().ordinal());
                        ps.setInt(4, mutation.getStandplaatsStatus().ordinal());
                        ps.setString(5, mutation.getStandplaatsGeometrie());
                        if (mutation.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(6, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(6,
                                    new Timestamp(mutation.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(7, mutation.getInOnderzoek().ordinal());
                        ps.setDate(8, new Date(mutation.getDocumentdatum().getTime()));
                        ps.setString(9, mutation.getDocumentnummer());
                        ps.setLong(10, mutation.getHoofdAdres());
                        ps.setLong(11, origineel.getIdentificatie());
                        ps.setLong(12, origineel.getAanduidingRecordCorrectie());
                        ps.setTimestamp(13,
                                new Timestamp(origineel.getBegindatumTijdvakGeldigheid().getTime()));
                        return ps;
                    }
                });
                deleteNevenadressen(TypeAdresseerbaarObject.STANDPLAATS, origineel);
                insertNevenadressen(TypeAdresseerbaarObject.STANDPLAATS, mutation);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error updating standplaats: " + origineel.getIdentificatie(), e);
    }
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insert(final Nummeraanduiding nummeraanduiding) throws DAOException {
    try {/*from  w w w  .  ja  va 2 s. c  o  m*/
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection
                        .prepareStatement("insert into bag_nummeraanduiding (" + "bag_nummeraanduiding_id,"
                                + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "huisnummer,"
                                + "officieel," + "huisletter," + "huisnummertoevoeging," + "postcode,"
                                + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid,"
                                + "in_onderzoek," + "type_adresseerbaar_object," + "bron_documentdatum,"
                                + "bron_documentnummer," + "nummeraanduiding_status," + "bag_woonplaats_id,"
                                + "bag_openbare_ruimte_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                ps.setLong(1, nummeraanduiding.getIdentificatie());
                ps.setInt(2, nummeraanduiding.getAanduidingRecordInactief().ordinal());
                ps.setLong(3, nummeraanduiding.getAanduidingRecordCorrectie());
                ps.setInt(4, nummeraanduiding.getHuisnummer());
                ps.setInt(5, nummeraanduiding.getOfficieel().ordinal());
                if (nummeraanduiding.getHuisletter() == null)
                    ps.setNull(6, Types.VARCHAR);
                else
                    ps.setString(6, nummeraanduiding.getHuisletter());
                if (nummeraanduiding.getHuisnummertoevoeging() == null)
                    ps.setNull(7, Types.VARCHAR);
                else
                    ps.setString(7, nummeraanduiding.getHuisnummertoevoeging());
                if (nummeraanduiding.getPostcode() == null)
                    ps.setNull(8, Types.VARCHAR);
                else
                    ps.setString(8, nummeraanduiding.getPostcode());
                ps.setTimestamp(9, new Timestamp(nummeraanduiding.getBegindatumTijdvakGeldigheid().getTime()));
                if (nummeraanduiding.getEinddatumTijdvakGeldigheid() == null)
                    ps.setNull(10, Types.TIMESTAMP);
                else
                    ps.setTimestamp(10,
                            new Timestamp(nummeraanduiding.getEinddatumTijdvakGeldigheid().getTime()));
                ps.setInt(11, nummeraanduiding.getInOnderzoek().ordinal());
                ps.setInt(12, nummeraanduiding.getTypeAdresseerbaarObject().ordinal());
                ps.setDate(13, new Date(nummeraanduiding.getDocumentdatum().getTime()));
                ps.setString(14, nummeraanduiding.getDocumentnummer());
                ps.setInt(15, nummeraanduiding.getNummeraanduidingStatus().ordinal());
                if (nummeraanduiding.getGerelateerdeWoonplaats() == null)
                    ps.setNull(16, Types.INTEGER);
                else
                    ps.setLong(16, nummeraanduiding.getGerelateerdeWoonplaats());
                ps.setLong(17, nummeraanduiding.getGerelateerdeOpenbareRuimte());
                return ps;
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting nummeraanduiding: " + nummeraanduiding.getIdentificatie(), e);
    }
}

From source file:com.funambol.foundation.items.dao.PIMNoteDAO.java

public void addItem(NoteWrapper nw) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("PIMNoteDAO addItem begin");
    }// w ww  .  j  av a  2 s  .c  om

    Connection con = null;
    PreparedStatement ps = null;

    long id = 0;
    String sId = null;

    Timestamp lastUpdate = nw.getLastUpdate();
    if (lastUpdate == null) {
        lastUpdate = new Timestamp(System.currentTimeMillis());
    }

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        // calculate table row id
        sId = nw.getId();
        if (sId == null) { // ...as it should be
            sId = getNextID();
            nw.setId(sId);
        }
        id = Long.parseLong(sId);

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_NOTE);

        int k = 1;
        //
        // GENERAL
        //

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with ID " + id);
        }
        ps.setLong(k++, id);

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with user ID " + userId);
        }
        ps.setString(k++, userId);

        ps.setLong(k++, lastUpdate.getTime());
        ps.setString(k++, String.valueOf(Def.PIM_STATE_NEW));

        Note note = nw.getNote();

        ps.setString(k++, StringUtils.left(note.getSubject().getPropertyValueAsString(), SQL_SUBJECT_DIM));

        String textDescription = note.getTextDescription().getPropertyValueAsString();
        if (textDescription != null) {
            textDescription = textDescription.replace('\0', ' ');
        }
        String truncatedTextDescription = StringUtils.left(textDescription, SQL_TEXTDESCRIPTION_DIM);
        ps.setString(k++, truncatedTextDescription);

        ps.setString(k++,
                truncateCategoriesField(note.getCategories().getPropertyValueAsString(), SQL_CATEGORIES_DIM));
        ps.setString(k++, truncateFolderField(note.getFolder().getPropertyValueAsString(), SQL_FOLDER_DIM));

        Property color = note.getColor();
        Property height = note.getHeight();
        Property width = note.getWidth();
        Property top = note.getTop();
        Property left = note.getLeft();

        if (Property.isEmptyProperty(color)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(color.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(height)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(height.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(width)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(width.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(top)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(top.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(left)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(left.getPropertyValueAsString()));
        }

        Long crc = calculateCrc(truncatedTextDescription);
        if (crc == null) {
            ps.setNull(k++, Types.BIGINT);
        } else {
            ps.setLong(k++, crc);
        }

        ps.executeUpdate();

    } catch (Exception e) {
        throw new DAOException("Error adding note.", e);
    } finally {
        DBTools.close(con, ps, null);
    }

    if (log.isTraceEnabled()) {
        log.trace("Added item with ID " + id);
        log.trace("PIMNoteDAO addItem end");
    }
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void update(final Verblijfsobject verblijfsobject) throws DAOException {
    try {//from   w ww.j  a  v  a  2 s.co m
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement("update bag_verblijfsobject set"
                                + " aanduiding_record_inactief = ?," + " officieel = ?,"
                                + " verblijfsobject_geometrie = ?," + " oppervlakte_verblijfsobject = ?,"
                                + " verblijfsobject_status = ?," + " einddatum_tijdvak_geldigheid = ?,"
                                + " in_onderzoek = ?," + " bron_documentdatum = ?,"
                                + " bron_documentnummer = ?," + " bag_nummeraanduiding_id = ?"
                                + " where bag_verblijfsobject_id = ?" + " and aanduiding_record_correctie = ?"
                                + " and begindatum_tijdvak_geldigheid = ?");
                        ps.setInt(1, verblijfsobject.getAanduidingRecordInactief().ordinal());
                        ps.setInt(2, verblijfsobject.getOfficieel().ordinal());
                        ps.setString(3, verblijfsobject.getVerblijfsobjectGeometrie());
                        ps.setInt(4, verblijfsobject.getOppervlakteVerblijfsobject());
                        ps.setInt(5, verblijfsobject.getVerblijfsobjectStatus().ordinal());
                        if (verblijfsobject.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(6, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(6,
                                    new Timestamp(verblijfsobject.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(7, verblijfsobject.getInOnderzoek().ordinal());
                        ps.setDate(8, new Date(verblijfsobject.getDocumentdatum().getTime()));
                        ps.setString(9, verblijfsobject.getDocumentnummer());
                        ps.setLong(10, verblijfsobject.getHoofdAdres());
                        ps.setLong(11, verblijfsobject.getIdentificatie());
                        ps.setLong(12, verblijfsobject.getAanduidingRecordCorrectie());
                        ps.setTimestamp(13,
                                new Timestamp(verblijfsobject.getBegindatumTijdvakGeldigheid().getTime()));
                        return ps;
                    }
                });
                deleteGebruikersdoelen(verblijfsobject);
                insertGebruikersdoelen(verblijfsobject);
                deleteNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, verblijfsobject);
                insertNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, verblijfsobject);
                deleteGerelateerdePanden(verblijfsobject);
                insertGerelateerdePanden(verblijfsobject);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error updating verblijfsobject: " + verblijfsobject.getIdentificatie(), e);
    }
}

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

@Override
@AutoTruncate//w  ww. j ava 2  s  .co m
public Contact modifyContact(AccessToken token, @DatabaseEntity Contact c)
        throws SQLException, FindException, EventNotFoundException, ServerFault {

    String q = "update Contact SET " + "contact_commonname=?, contact_firstname=?, "
            + "contact_lastname=?, contact_origin=?, contact_userupdate=?, "
            + "contact_aka=?, contact_title=?, contact_service=?, contact_company=?, contact_comment=?, "
            + "contact_suffix=?, contact_manager=?, contact_middlename=?, contact_assistant=?, contact_spouse=?, contact_anniversary_id=?, contact_birthday_id=? "
            + "WHERE contact_id=? ";
    logger.info("modify contact with id=" + c.getUid() + " entityId=" + c.getEntityId());

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = obmHelper.getConnection();

        EventObmId anniversaryId = createOrUpdateDate(token, con, c, c.getAnniversary(), ANNIVERSARY_FIELD);
        c.setAnniversaryId(anniversaryId);

        EventObmId birthdayId = createOrUpdateDate(token, con, c, c.getBirthday(), BIRTHDAY_FIELD);
        c.setBirthdayId(birthdayId);

        ps = con.prepareStatement(q);

        int idx = 1;
        ps.setString(idx++, c.getCommonname());
        ps.setString(idx++, c.getFirstname());
        ps.setString(idx++, c.getLastname());
        ps.setString(idx++, token.getOrigin());
        ps.setInt(idx++, token.getObmId());

        ps.setString(idx++, c.getAka());
        ps.setString(idx++, c.getTitle());
        ps.setString(idx++, c.getService());
        ps.setString(idx++, c.getCompany());
        ps.setString(idx++, c.getComment());

        ps.setString(idx++, c.getSuffix());
        ps.setString(idx++, c.getManager());
        ps.setString(idx++, c.getMiddlename());
        ps.setString(idx++, c.getAssistant());
        ps.setString(idx++, c.getSpouse());
        if (c.getAnniversaryId() == null) {
            ps.setNull(idx++, Types.INTEGER);
        } else {
            ps.setInt(idx++, c.getAnniversaryId().getObmId());
        }
        if (c.getBirthdayId() == null) {
            ps.setNull(idx++, Types.INTEGER);
        } else {
            ps.setInt(idx++, c.getBirthdayId().getObmId());
        }

        ps.setInt(idx++, c.getUid());
        ps.executeUpdate();

        createOrUpdateAddresses(con, c.getEntityId(), c.getAddresses());
        createOrUpdateEmails(con, c.getEntityId(), c.getEmails());
        createOrUpdatePhones(con, c.getEntityId(), c.getPhones());
        createOrUpdateWebsites(con, c);
        createOrUpdateIMIdentifiers(con, c.getEntityId(), c.getImIdentifiers());
    } finally {
        obmHelper.cleanup(con, ps, null);
    }

    indexContact(token, c);

    return c;
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

/**
 * Register configs in derby database. This method will insert the ids
 * generated by the repository into the configs passed in itself.
 *
 * Use given prepared statements to create entire config structure in database.
 *
 * @param configurableId//from www .  j  a  v  a 2 s .  c om
 * @param configs
 * @param type
 * @param baseConfigStmt
 * @param baseInputStmt
 * @param conn
 * @return short number of configs registered.
 * @throws SQLException
 */
private short registerConfigs(Long configurableId, Direction direction, List<MConfig> configs, String type,
        PreparedStatement baseConfigStmt, PreparedStatement baseInputStmt, Connection conn)
        throws SQLException {
    short configIndex = 0;

    for (MConfig config : configs) {
        if (configurableId == null) {
            baseConfigStmt.setNull(1, Types.BIGINT);
        } else {
            baseConfigStmt.setLong(1, configurableId);
        }

        baseConfigStmt.setString(2, config.getName());
        baseConfigStmt.setString(3, type);
        baseConfigStmt.setShort(4, configIndex++);

        int baseConfigCount = baseConfigStmt.executeUpdate();
        if (baseConfigCount != 1) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0015, Integer.toString(baseConfigCount));
        }
        ResultSet rsetConfigId = baseConfigStmt.getGeneratedKeys();
        if (!rsetConfigId.next()) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0016);
        }

        long configId = rsetConfigId.getLong(1);
        config.setPersistenceId(configId);

        if (direction != null) {
            registerConfigDirection(configId, direction, conn);
        }

        // Insert all the inputs
        List<MInput<?>> inputs = config.getInputs();
        registerConfigInputs(configId, inputs, baseInputStmt);
    }
    return configIndex;
}

From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

/**
 * bind the variables to the prepared statement
 * /*from   ww  w.j  av  a 2 s .c  om*/
 * @param type
 * @param mapInfo
 * @param ps
 * @param annoId
 * @param anno
 * @throws SQLException
 */
private void saveAnnoBindVariables(final Type type, final AnnoMappingInfo mapInfo, PreparedStatement ps,
        int annoId, FeatureStructure anno, final BiMap<Annotation, Integer> mapAnnoToId) throws SQLException {
    // set anno_base_id
    int argIdx = 1;
    ps.setInt(argIdx++, annoId);
    if (mapInfo.getCoveredTextColumn() != null) {
        String trunc = null;
        if (anno instanceof Annotation) {
            trunc = truncateString(((Annotation) anno).getCoveredText(),
                    mapInfo.getCoveredTextColumn().getSize());
        }
        ps.setString(argIdx++, trunc);
    }
    if (!Strings.isNullOrEmpty(mapInfo.getUimaTypeIdColumnName())) {
        ps.setInt(argIdx++, mapInfo.getUimaTypeId());
    }
    // iterate over fields
    for (Map.Entry<String, ColumnMappingInfo> fieldEntry : mapInfo.getMapField().entrySet()) {
        ColumnMappingInfo fieldMapInfo = fieldEntry.getValue();
        String fieldName = fieldMapInfo.getAnnoFieldName();
        Feature feat = type.getFeatureByBaseName(fieldName);
        if (fieldMapInfo.getConverter() != null) {
            try {
                String prop = anno.getFeatureValueAsString(feat);
                ps.setObject(argIdx, fieldMapInfo.getConverter().convert(fieldMapInfo.getTargetType(), prop));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (!feat.getRange().isPrimitive()) {
            // feature is a structure/annotation
            FeatureStructure fs = anno.getFeatureValue(feat);
            if (fs == null) {
                // feature is null - set the column to null
                ps.setNull(argIdx, fieldMapInfo.getSqlType());
            } else {
                if (fieldMapInfo.getJxpath() != null) {
                    // jxpath to pull out feature attribute
                    Object o = this.extractFeature(fieldMapInfo.getJxpath(), fs);
                    if (o == null) {
                        // extracted value null - set column to null
                        ps.setNull(argIdx, fieldMapInfo.getSqlType());
                    } else if (o instanceof String) {
                        // string - truncate as needed
                        String trunc = truncateString((String) o, fieldMapInfo.getSize());
                        ps.setString(argIdx, trunc);
                    } else {
                        // set value
                        ps.setObject(argIdx, o);
                    }
                } else {
                    // reference to another annotation - get the other
                    // anno's id
                    Integer refAnnoId = null;
                    if (fs instanceof Annotation) {
                        refAnnoId = mapAnnoToId.get(fs);
                    }
                    if (refAnnoId != null) {
                        ps.setInt(argIdx, refAnnoId);
                    } else {
                        ps.setNull(argIdx, Types.INTEGER);
                    }
                }
            }
        } else {
            if ("uima.cas.Integer".equals(feat.getRange().getName())) {
                ps.setInt(argIdx, anno.getIntValue(feat));
            } else if ("uima.cas.Short".equals(feat.getRange().getName())) {
                ps.setShort(argIdx, anno.getShortValue(feat));
            } else if ("uima.cas.Long".equals(feat.getRange().getName())) {
                ps.setLong(argIdx, anno.getLongValue(feat));
            } else if ("uima.cas.Float".equals(feat.getRange().getName())) {
                ps.setFloat(argIdx, anno.getFloatValue(feat));
            } else if ("uima.cas.Double".equals(feat.getRange().getName())) {
                ps.setDouble(argIdx, anno.getDoubleValue(feat));
            } else if ("uima.cas.Byte".equals(feat.getRange().getName())) {
                ps.setByte(argIdx, anno.getByteValue(feat));
            } else if ("uima.cas.Boolean".equals(feat.getRange().getName())) {
                ps.setBoolean(argIdx, anno.getBooleanValue(feat));
            } else if ("uima.cas.String".equals(feat.getRange().getName())) {
                String trunc = truncateString(anno.getStringValue(feat), fieldMapInfo.getSize());
                ps.setString(argIdx, trunc);
            }
        }
        argIdx++;
    }
}

From source file:com.silverwrist.dynamo.security.AuditWriteOps_mysql.java

void writeAuditRecord(PropertyKey event, java.util.Date timestamp, int uid, int subid, String ip,
        Object[] props) throws DatabaseException {
    Connection conn = null;//from   w ww .  j ava  2 s  .  co m
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    try { // get a connection
        conn = getConnection();
        stmt2 = conn.createStatement();

        // First subphase is to get the event ID corresponding to this event; if it doesn't exist,
        // we need to create it.
        int event_id = -1;
        Integer id_val = (Integer) (m_eventid_cache.get(event));
        if (id_val != null) // found it in our own cache
            event_id = id_val.intValue();
        if (event_id < 0) { // OK, we didn't find it locally, go out to the database and look.
            ResultSet rs = null;
            try { // lock the "auditevent" table until we can do what we have to
                stmt2.executeUpdate("LOCK TABLES auditevent WRITE;");

                // look up the event ID
                stmt = conn.prepareStatement(
                        "SELECT eventid FROM auditevent WHERE event_nsid = ? " + "AND event_name = ?;");
                stmt.setInt(1, event.getNamespaceID());
                stmt.setString(2, event.getName());
                rs = stmt.executeQuery();
                if (rs.next())
                    event_id = rs.getInt(1);
                else { // insert a new record and get a new, dynamically-generated event ID
                    SQLUtils.shutdown(stmt);
                    stmt = conn
                            .prepareStatement("INSERT INTO auditevent (event_nsid, event_name) VALUES (?, ?);");
                    stmt.setInt(1, event.getNamespaceID());
                    stmt.setString(2, event.getName());
                    stmt.executeUpdate();
                    event_id = MySQLUtils.getLastInsertInt(conn);

                } // end else

            } // end try
            finally { // unlock the table once we're done here
                MySQLUtils.unlockTables(conn);
                SQLUtils.shutdown(rs);

            } // end finally

            m_eventid_cache.put(event, new Integer(event_id)); // and cache it for next time

        } // end if

        try { // lock the "audit" table for writing
            stmt2.executeUpdate("LOCK TABLES audit WRITE;");

            // prepare the big statement
            stmt = conn.prepareStatement("INSERT INTO audit (on_date, event, uid, subid, ip, prop0, prop1, "
                    + "prop2, prop3, prop4, prop5, prop6, prop7) VALUES "
                    + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
            m_utils.setDateTime(stmt, 1, timestamp);
            stmt.setInt(2, event_id);
            stmt.setInt(3, uid);
            stmt.setInt(4, subid);
            stmt.setString(5, ip);
            for (int i = 0; i < props.length; i++) { // set all the property values
                if (props[i] == null)
                    stmt.setNull(6 + i, Types.VARCHAR);
                else { // serialize the property
                    String s = m_psz.serializeProperty(props[i]);
                    if (s == null)
                        throw new DatabaseException(AuditWriteOps_mysql.class, "SecurityMessages",
                                "audit.serialize");
                    stmt.setString(6 + i, s);

                } // end else

            } // end for

            stmt.executeUpdate(); // chunk it out!

        } // end try
        finally { // and unlock this table once we're done here
            MySQLUtils.unlockTables(conn);

        } // end finally

    } // end try
    catch (SQLException e) { // translate to a general DatabaseException
        throw generalException(e);

    } // end catch
    finally { // shut everything down
        SQLUtils.shutdown(stmt);
        SQLUtils.shutdown(stmt2);
        SQLUtils.shutdown(conn);

    } // end finally

}