Example usage for java.sql PreparedStatement setObject

List of usage examples for java.sql PreparedStatement setObject

Introduction

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

Prototype

void setObject(int parameterIndex, Object x) throws SQLException;

Source Link

Document

Sets the value of the designated parameter using the given object.

Usage

From source file:org.efaps.admin.datamodel.Attribute.java

/**
 * @param _type Type the attributes are wanted for
 * @throws EFapsException on error/*from   w w  w .  j  a  va  2 s.co m*/
 */
protected static void add4Type(final Type _type) throws EFapsException {
    ConnectionResource con = null;
    try {
        con = Context.getThreadContext().getConnectionResource();
        PreparedStatement stmt = null;
        final List<Object[]> values = new ArrayList<Object[]>();
        try {
            stmt = con.getConnection().prepareStatement(Attribute.SQL_TYPE);
            stmt.setObject(1, _type.getId());
            final ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                values.add(new Object[] { rs.getLong(1), rs.getString(2).trim(), rs.getLong(3), rs.getLong(4),
                        rs.getLong(5), rs.getLong(6), rs.getLong(7), rs.getString(8), rs.getString(9),
                        rs.getString(10), rs.getString(11) });
            }
            rs.close();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        con.commit();

        final Map<Long, AttributeSet> id2Set = new HashMap<Long, AttributeSet>();
        final Map<Attribute, Long> attribute2setId = new HashMap<Attribute, Long>();
        final List<Attribute> attributes = new ArrayList<Attribute>();
        for (final Object[] row : values) {
            final long id = (Long) row[0];
            final String name = (String) row[1];
            final long typeAttrId = (Long) row[2];
            final long tableId = (Long) row[3];
            final long attrTypeId = (Long) row[4];
            final long typeLinkId = (Long) row[5];
            final long parentSetId = (Long) row[6];
            final String sqlCol = (String) row[7];
            final String defaultval = (String) row[8];
            final String dimensionUUID = (String) row[9];
            final String className = (String) row[10];

            Attribute.LOG.debug("read attribute '{}/{}' (id = {})", _type.getName(), name, id);

            if (Type.check4Type(typeAttrId, CIAdminDataModel.AttributeSet.uuid)) {
                final AttributeSet set = new AttributeSet(id, _type, name, AttributeType.get(attrTypeId),
                        sqlCol, tableId, typeLinkId, dimensionUUID);
                id2Set.put(id, set);
            } else {
                final Attribute attr = new Attribute(id, _type.getId(), name, sqlCol, SQLTable.get(tableId),
                        AttributeType.get(attrTypeId), defaultval, dimensionUUID);

                final UUID uuid = attr.getAttributeType().getUUID();
                if (uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_LINK.getUuid())
                        || uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_LINK_WITH_RANGES.getUuid())
                        || uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_STATUS.getUuid())) {
                    attr.setLink(typeLinkId);
                    // in case of a PersonLink, CreatorLink or ModifierLink a link to Admin_User_Person
                    // must be set
                } else if (uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_CREATOR_LINK.getUuid())
                        || uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_MODIFIER_LINK.getUuid())
                        || uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_PERSON_LINK.getUuid())) {
                    attr.setLink(Type.getId4UUID(CIAdminUser.Person.uuid));
                    // in case of a GroupLink, a link to Admin_User_Group must be set
                } else if (uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_GROUP_LINK.getUuid())) {
                    attr.setLink(Type.getId4UUID(CIAdminUser.Group.uuid));
                    // in case of a Enum and BitEnum the className must be set
                } else if (uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_ENUM.getUuid())
                        || uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_BITENUM.getUuid())
                        || uuid.equals(Attribute.AttributeTypeDef.ATTRTYPE_JAXB.getUuid())) {
                    if (className == null || className != null && className.isEmpty()) {
                        Attribute.LOG.error(
                                "An Attribute of Type Enum, BitEnum, Jaxb must have a className: {}", attr);
                    }
                    attr.setClassName(className.trim());
                }
                attr.readFromDB4Properties();

                if (Type.check4Type(typeAttrId, CIAdminDataModel.AttributeSetAttribute.uuid)) {
                    attribute2setId.put(attr, parentSetId);
                } else {
                    attributes.add(attr);
                    Attribute.cacheAttribute(attr, _type);
                }
            }
        }
        // make connection between set and attributes
        for (final Entry<Attribute, Long> entry : attribute2setId.entrySet()) {
            final AttributeSet parentset = id2Set.get(entry.getValue());
            final Attribute childAttr = entry.getKey();
            parentset.addAttributes(false, childAttr);
            childAttr.setParentSet(parentset);
            // needed due to cluster serialization that does not update automatically
            Attribute.cacheAttribute(childAttr, parentset);
        }
        for (final AttributeSet set : id2Set.values()) {
            Type.cacheType(set);
        }

        _type.addAttributes(false, attributes.toArray(new Attribute[attributes.size()]));
    } catch (final SQLException e) {
        throw new CacheReloadException("Cannot read attributes.", e);
    } finally {
        if (con != null && con.isOpened()) {
            con.abort();
        }
    }
}

From source file:ips1ap101.lib.core.db.util.DB.java

public static PreparedStatement prepareStatement(Connection connection, String sql, Object[] args) {
    PreparedStatement preparedStatement;
    if (connection != null && sql != null) {
        try {//from w  ww.jav a  2 s .  co  m
            preparedStatement = connection.prepareStatement(sql);
            int n = args == null ? 0 : args.length;
            if (n > 0) {
                for (int i = 0; i < n; i++) {
                    if (args[i] == null) {
                        //                          callableStatement.setNull(i + 1, java.sql.Types.OTHER);
                        preparedStatement.setNull(i + 1, java.sql.Types.NULL);
                    } else if (args[i] instanceof EnumTipoDatoSQL) {
                        EnumTipoDatoSQL tipoDatoSQL = (EnumTipoDatoSQL) args[i];
                        preparedStatement.setNull(i + 1, tipoDatoSQL.intValue());
                    } else {
                        preparedStatement.setObject(i + 1, args[i]);
                    }
                }
            }
            return preparedStatement;
        } catch (SQLException ex) {
            Bitacora.logFatal(ex);
        }
    }
    return null;
}

From source file:org.rhq.plugins.database.DatabasePluginUtil.java

private static void bindParameters(PreparedStatement statement, Object... parameters) throws SQLException {
    int i = 1;/*www  .j ava  2 s.c om*/
    for (Object p : parameters) {
        if (p instanceof String) {
            statement.setString(i++, (String) p);
        } else if (p instanceof Byte) {
            statement.setByte(i++, (Byte) p);
        } else if (p instanceof Short) {
            statement.setShort(i++, (Short) p);
        } else if (p instanceof Integer) {
            statement.setInt(i++, (Integer) p);
        } else if (p instanceof Long) {
            statement.setLong(i++, (Long) p);
        } else if (p instanceof Float) {
            statement.setFloat(i++, (Float) p);
        } else if (p instanceof Double) {
            statement.setDouble(i++, (Double) p);
        } else {
            statement.setObject(i++, p);
        }
    }
}

From source file:com.adaptris.core.services.jdbc.DoubleStatementParameter.java

@Override
public void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException, ServiceException {
    log.trace("Setting argument {} to [{}]", parameterIndex, getQueryValue(msg));
    statement.setObject(parameterIndex, toDouble(getQueryValue(msg)));
}

From source file:com.adaptris.core.services.jdbc.LongStatementParameter.java

@Override
public void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException, ServiceException {
    log.trace("Setting argument {} to [{}]", parameterIndex, getQueryValue(msg));
    statement.setObject(parameterIndex, toLong(getQueryValue(msg)));
}

From source file:com.adaptris.core.services.jdbc.ShortStatementParameter.java

@Override
public void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException, ServiceException {
    log.trace("Setting argument {} to [{}]", parameterIndex, getQueryValue(msg));
    statement.setObject(parameterIndex, toShort(getQueryValue(msg)));
}

From source file:com.adaptris.core.services.jdbc.FloatStatementParameter.java

@Override
public void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException, ServiceException {
    log.trace("Setting argument {} to [{}]", parameterIndex, getQueryValue(msg));
    statement.setObject(parameterIndex, toFloat(getQueryValue(msg)));
}

From source file:com.adaptris.core.services.jdbc.IntegerStatementParameter.java

@Override
public void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException, ServiceException {
    log.trace("Setting argument {} to [{}]", parameterIndex, getQueryValue(msg));
    statement.setObject(parameterIndex, toInteger(getQueryValue(msg)));
}

From source file:org.gbif.harvest.portal.synchronise.dao.jdbc.ImageRecordDaoImpl.java

public long create(final ImageRecord imageRecord) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(ImageRecordDaoImpl.CREATE_SQL);
            ps.setLong(1, imageRecord.getDataResourceId());
            ps.setObject(2, imageRecord.getOccurrenceId());
            ps.setLong(3, imageRecord.getTaxonConceptId());
            ps.setString(4,/*from www.ja  v  a 2s .c o m*/
                    StringUtils.trimToNull(StringUtils.replace(StringUtils
                            .replace(StringUtils.replace(imageRecord.getRawImageType(), "\n", " "), "\r", " "),
                            "\t", " ")));
            ps.setInt(5, imageRecord.getImageType());
            ps.setString(6, StringUtils.trimToNull(StringUtils.replace(
                    StringUtils.replace(StringUtils.replace(imageRecord.getUrl(), "\n", " "), "\r", " "), "\t",
                    " ")));
            ps.setString(7,
                    StringUtils.trimToNull(StringUtils.replace(StringUtils
                            .replace(StringUtils.replace(imageRecord.getDescription(), "\n", " "), "\r", " "),
                            "\t", " ")));
            ps.setString(8, StringUtils.trimToNull(StringUtils.replace(
                    StringUtils.replace(StringUtils.replace(imageRecord.getRights(), "\n", " "), "\r", " "),
                    "\t", " ")));
            ps.setString(9,
                    StringUtils.trimToNull(StringUtils.replace(
                            StringUtils.replace(StringUtils.replace(imageRecord.getHtmlForDisplay(), "\n", " "),
                                    "\r", " "),
                            "\t", " ")));
            return ps;
        }
    }, keyHolder);
    imageRecord.setId(keyHolder.getKey().longValue());
    return keyHolder.getKey().longValue();
}

From source file:com.bosscs.spark.jdbc.writer.JdbcWriter.java

/**
 * Saves data./*from w  ww.  ja v a  2 s .  c  o m*/
 * @param row Data structure representing a row as a Map of column_name:column_value
 * @throws SQLException
 */
public void save(Map<String, Object> row) throws Exception {
    Tuple2<List<String>, String> data = sqlFromRow(row);
    PreparedStatement statement = conn.prepareStatement(data._2());
    int i = 1;
    for (String columnName : data._1()) {
        statement.setObject(i, row.get(columnName));
        i++;
    }
    statement.executeUpdate();
}