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:com.vigglet.util.ModelUtilBase.java

protected T insertOrUpdate(T model, List<Object> values) {
    T result = null;/*from  w  w  w.jav  a2 s . c o  m*/

    try {
        PreparedStatement stmt = null;
        if (model.getId() > 0) {
            stmt = getUpdateStatement();
        } else {
            stmt = getInsertStatement();
        }

        int i = 1;
        for (Object obj : values) {
            stmt.setObject(i++, obj);
        }

        if (model.getId() > 0) {
            stmt.setInt(i++, model.getId());
        }

        stmt.executeUpdate();

        int id = 0;
        if (model.getId() > 0) {
            id = model.getId();
        } else {
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                id = rs.getInt(1);
            }
            rs.close();
        }

        result = findById(id);

        stmt.close();
    } catch (SQLException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:de.tu_berlin.dima.oligos.db.JdbcConnector.java

/**
 * @deprecated As of 0.3.1, public methods should not return <code>ResultSet</code>.
 * @param query/*from  w w  w  .  j  a  v  a2  s  .  co m*/
 * @param parameters
 * @return
 * @throws SQLException
 */
@Deprecated
public ResultSet executeQuery(final String query, final Object... parameters) throws SQLException {
    PreparedStatement stmt = connection.prepareStatement(query);
    for (int i = 1; i <= parameters.length; i++) {
        stmt.setObject(i, parameters[i - 1]);
    }
    ResultSet result = stmt.executeQuery();
    return result;
}

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

/**
 * @param _parentID id to be searched for
 * @param _statement statement to be executed
 * @return a list of object containing the id and the purpose
 * @throws CacheReloadException on error
 *//*www . j a  v a2s  .c  om*/
private static List<Object[]> getChildTypeIDs(final long _parentID, final String _statement)
        throws CacheReloadException {
    final List<Object[]> ret = new ArrayList<Object[]>();
    ConnectionResource con = null;
    try {
        con = Context.getThreadContext().getConnectionResource();
        PreparedStatement stmt = null;
        try {
            stmt = con.getConnection().prepareStatement(_statement);
            stmt.setObject(1, _parentID);
            final ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                ret.add(new Object[] { rs.getLong(1), rs.getInt(2) });
            }
            rs.close();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        con.commit();
    } catch (final SQLException e) {
        throw new CacheReloadException("could not read child type ids", e);
    } catch (final EFapsException e) {
        throw new CacheReloadException("could not read child type ids", e);
    } finally {
        if (con != null && con.isOpened()) {
            try {
                con.abort();
            } catch (final EFapsException e) {
                throw new CacheReloadException("could not read child type ids", e);
            }
        }
    }
    return ret;
}

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

/**
 * @param _sql SQLStatement to be executed
 * @param _criteria the filter criteria//  www.  ja v  a2  s . c o m
 * @return Type instance
 * @throws CacheReloadException on error
 */
private static Type getTypeFromDB(final String _sql, final Object _criteria) throws CacheReloadException {
    Type ret = null;
    ConnectionResource con = null;
    try {
        con = Context.getThreadContext().getConnectionResource();
        final PreparedStatement stmt = con.getConnection().prepareStatement(_sql);
        stmt.setObject(1, _criteria);
        final ResultSet rs = stmt.executeQuery();
        long parentTypeId = 0;
        long parentClassTypeId = 0;
        long id = 0;

        if (rs.next()) {
            id = rs.getLong(1);
            final String uuid = rs.getString(2).trim();
            final String name = rs.getString(3).trim();
            final int purpose = rs.getInt(4);
            parentTypeId = rs.getLong(5);
            parentClassTypeId = rs.getLong(6);

            Type.LOG.debug(
                    "read type '{}' (id = {}) (purpose = {}) (parentTypeId = {}) (parentClassTypeId = {})",
                    name, id, purpose, parentTypeId, parentClassTypeId);

            if (BitEnumType.isSelected(purpose, Type.Purpose.CLASSIFICATION)) {
                ret = new Classification(id, uuid, name);
                if (parentClassTypeId != 0) {
                    ((Classification) ret).setParentClassification(parentClassTypeId);
                }
            } else {
                ret = new Type(id, uuid, name);
            }
            if (parentTypeId != 0) {
                ret.setParentTypeID(parentTypeId);
            }
            ret.setAbstract(BitEnumType.isSelected(purpose, Type.Purpose.ABSTRACT));
            ret.setHistory(BitEnumType.isSelected(purpose, Type.Purpose.HISTORY));
            if (BitEnumType.isSelected(purpose, Type.Purpose.GENERALINSTANCE)) {
                ret.setGeneralInstance(true);
            }
            if (BitEnumType.isSelected(purpose, Type.Purpose.NOGENERALINSTANCE)) {
                ret.setGeneralInstance(false);
            }
        }
        rs.close();
        stmt.close();
        con.commit();
        if (ret != null) {
            if (parentTypeId != 0) {
                Type.LOG.trace("get parent for id = {}", parentTypeId);
                final Type parent = Type.get(parentTypeId);
                // TODO: test if loop
                if (ret.getId() == parent.getId()) {
                    throw new CacheReloadException("child and parent type is equal!child is " + ret);
                }
            }
            if (!ret.checked4Children) {
                ret.checked4Children = true;
                for (final Object[] childIDs : Type.getChildTypeIDs(ret.getId(), Type.SQL_CHILD)) {
                    Type.LOG.trace("reading Child Type with id: {} for type :{}", childIDs[0], ret.getName());
                    ret.childTypes.add((Long) childIDs[0]);
                }
                if (ret instanceof Classification) {
                    for (final Object[] childIDs : Type.getChildTypeIDs(ret.getId(), Type.SQL_CLASSCHILD)) {
                        Type.LOG.trace("reading Child class Type with id: {} for type :{}", childIDs[0],
                                ret.getName());
                        ((Classification) ret).getChildren().add((Long) childIDs[0]);
                    }
                }
                ret.setDirty();
            }
            Attribute.add4Type(ret);
            ret.readFromDB4Links();
            ret.readFromDB4Properties();
            ret.inheritAttributes();
            // needed due to cluster serialization that does not update automatically
            Type.cacheType(ret);
            Type.LOG.trace("ended reading type '{}'", ret.getName());
        }
    } catch (final EFapsException e) {
        Type.LOG.error("initialiseCache()", e);
    } catch (final SQLException e) {
        Type.LOG.error("initialiseCache()", e);
    } finally {
        if (con != null && con.isOpened()) {
            try {
                con.abort();
            } catch (final EFapsException e) {
                throw new CacheReloadException("could not read child tyep ids", e);
            }
        }
    }
    return ret;
}

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

/**
 * During the initial caching of types, the mapping does not exists but is necessary.
 * @param _typeId id of the type the UUID is wanted for
 * @return id of the type// w  w  w. jav a 2s .com
 * @throws CacheReloadException on error
 */
public static UUID getUUID4Id(final long _typeId) throws CacheReloadException {
    UUID ret = null;
    final Cache<Long, Type> cache = InfinispanCache.get().<Long, Type>getCache(Type.IDCACHE);
    if (cache.containsKey(_typeId)) {
        ret = cache.get(_typeId).getUUID();
    } else {
        ConnectionResource con = null;
        try {
            con = Context.getThreadContext().getConnectionResource();
            PreparedStatement stmt = null;
            try {
                stmt = con.getConnection().prepareStatement(Type.SQL_ID);
                stmt.setObject(1, _typeId);
                final ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    ret = UUID.fromString(rs.getString(2).trim());
                }
                rs.close();
            } finally {
                if (stmt != null) {
                    stmt.close();
                }
            }
            con.commit();
        } catch (final SQLException e) {
            throw new CacheReloadException("could not read child type ids", e);
        } catch (final EFapsException e) {
            throw new CacheReloadException("could not read child type ids", e);
        } finally {
            if (con != null && con.isOpened()) {
                try {
                    con.abort();
                } catch (final EFapsException e) {
                    throw new CacheReloadException("could not read child type ids", e);
                }
            }
        }
    }
    return ret;
}

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

/**
 * Compares a given id and uuid of a type to evaluate if they are from the
 * same Type. In case that they are not cached (during initialize) teh
 * database is requested./* ww w .  ja  v a  2s . com*/
 *
 * @param _typeId Id of the type to be checked
 * @param _typeUUID uuid of the type to be checked
 * @return true if the id and the uuid belong to the same type
 * @throws CacheReloadException on error
 */
protected static boolean check4Type(final long _typeId, final UUID _typeUUID) throws CacheReloadException {
    boolean ret = false;
    final Cache<Long, Type> cache = InfinispanCache.get().<Long, Type>getCache(Type.IDCACHE);
    if (cache.containsKey(_typeId)) {
        ret = cache.get(_typeId).getUUID().equals(_typeUUID);
    } else {
        ConnectionResource con = null;
        String uuidTmp = "";
        try {
            con = Context.getThreadContext().getConnectionResource();
            PreparedStatement stmt = null;
            try {
                stmt = con.getConnection().prepareStatement(Type.SQL_ID);
                stmt.setObject(1, _typeId);
                final ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    uuidTmp = rs.getString(2).trim();
                }
                rs.close();
            } finally {
                if (stmt != null) {
                    stmt.close();
                }
            }
            con.commit();
        } catch (final SQLException e) {
            throw new CacheReloadException("could not read child type ids", e);
        } catch (final EFapsException e) {
            throw new CacheReloadException("could not read child type ids", e);
        } finally {
            if (con != null && con.isOpened()) {
                try {
                    con.abort();
                } catch (final EFapsException e) {
                    throw new CacheReloadException("could not read child type ids", e);
                }
            }
        }
        ret = UUID.fromString(uuidTmp).equals(_typeUUID);
    }
    return ret;
}

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

/**
 * During the initial caching of types, the mapping does not exists but is necessary.
 * @param _typeUUID UUID of the type the id is wanted for
 * @return id of the type//from  ww w  . jav  a2 s. c o m
 * @throws CacheReloadException on error
 */
protected static long getId4UUID(final UUID _typeUUID) throws CacheReloadException {
    long ret = 0;
    final Cache<UUID, Type> cache = InfinispanCache.get().<UUID, Type>getCache(Type.UUIDCACHE);
    if (cache.containsKey(_typeUUID)) {
        ret = cache.get(_typeUUID).getId();
    } else {
        ConnectionResource con = null;
        try {
            con = Context.getThreadContext().getConnectionResource();
            PreparedStatement stmt = null;
            try {
                stmt = con.getConnection().prepareStatement(Type.SQL_UUID);
                stmt.setObject(1, _typeUUID.toString());
                final ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    ret = rs.getLong(1);
                }
                rs.close();
            } finally {
                if (stmt != null) {
                    stmt.close();
                }
            }
            con.commit();
        } catch (final SQLException e) {
            throw new CacheReloadException("could not read child type ids", e);
        } catch (final EFapsException e) {
            throw new CacheReloadException("could not read child type ids", e);
        } finally {
            if (con != null && con.isOpened()) {
                try {
                    con.abort();
                } catch (final EFapsException e) {
                    throw new CacheReloadException("could not read child type ids", e);
                }
            }
        }
    }
    return ret;
}

From source file:org.opencron.server.dao.HibernateDao.java

@Transactional(readOnly = false)
public void executeBatch(final String sql, final Object[]... parameters) {
    getSession().doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            connection.setAutoCommit(false);
            PreparedStatement stmt = connection.prepareStatement(sql);
            for (Object[] arr : parameters) {
                int i = 1;
                for (Object p : arr) {
                    stmt.setObject(i++, p);
                }//from ww  w . ja v a  2 s  .  com
                stmt.addBatch();
            }
            stmt.executeBatch();
            connection.commit();
        }
    });
}

From source file:org.apache.hive.hplsql.Copy.java

/**
 * Copy the query results to another table
 * @throws Exception /*w w  w.  j  av a 2s  . c  o  m*/
 */
void copyToTable(HplsqlParser.Copy_stmtContext ctx, Query query) throws Exception {
    ResultSet rs = query.getResultSet();
    if (rs == null) {
        return;
    }
    ResultSetMetaData rm = rs.getMetaData();
    int cols = rm.getColumnCount();
    int rows = 0;
    if (trace) {
        trace(ctx, "SELECT executed: " + cols + " columns");
    }
    Connection conn = exec.getConnection(targetConn);
    StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO " + sqlInsertName + " VALUES (");
    for (int i = 0; i < cols; i++) {
        sql.append("?");
        if (i + 1 < cols) {
            sql.append(",");
        }
    }
    sql.append(")");
    PreparedStatement ps = conn.prepareStatement(sql.toString());
    long start = timer.start();
    long prev = start;
    boolean batchOpen = false;
    while (rs.next()) {
        for (int i = 1; i <= cols; i++) {
            ps.setObject(i, rs.getObject(i));
        }
        rows++;
        if (batchSize > 1) {
            ps.addBatch();
            batchOpen = true;
            if (rows % batchSize == 0) {
                ps.executeBatch();
                batchOpen = false;
            }
        } else {
            ps.executeUpdate();
        }
        if (trace && rows % 100 == 0) {
            long cur = timer.current();
            if (cur - prev > 10000) {
                trace(ctx, "Copying rows: " + rows + " (" + rows / ((cur - start) / 1000) + " rows/sec)");
                prev = cur;
            }
        }
    }
    if (batchOpen) {
        ps.executeBatch();
    }
    ps.close();
    exec.returnConnection(targetConn, conn);
    exec.setRowCount(rows);
    long elapsed = timer.stop();
    if (info) {
        info(ctx, "COPY completed: " + rows + " row(s), " + timer.format() + ", " + rows / (elapsed / 1000)
                + " rows/sec");
    }
}

From source file:cz.lbenda.dataman.db.RowDesc.java

@SuppressWarnings("ConstantConditions")
private <T> void putToPS(ColumnDesc columnDesc, T value, PreparedStatement ps, int position)
        throws SQLException {
    if (value == null) {
        ps.setObject(position, null);
        return;//from   ww w  .j a  v a  2 s  .  c o m
    }
    BinaryData bd = value instanceof BinaryData ? (BinaryData) value : null;
    switch (columnDesc.getDataType()) {
    case STRING:
        ps.setString(position, (String) value);
        break;
    case BOOLEAN:
        ps.setBoolean(position, (Boolean) value);
        break;
    case TIMESTAMP:
        ps.setTimestamp(position, (Timestamp) value);
        break;
    case DATE:
        ps.setDate(position, (Date) value);
        break;
    case TIME:
        ps.setTime(position, (Time) value);
        break;
    case BYTE:
        ps.setByte(position, (Byte) value);
        break;
    case SHORT:
        ps.setShort(position, (Short) value);
        break;
    case INTEGER:
        ps.setInt(position, (Integer) value);
        break;
    case LONG:
        ps.setLong(position, (Long) value);
        break;
    case FLOAT:
        ps.setFloat(position, (Float) value);
        break;
    case DOUBLE:
        ps.setDouble(position, (Double) value);
        break;
    case DECIMAL:
        ps.setBigDecimal(position, (BigDecimal) value);
        break;
    case UUID:
        ps.setBytes(position, AbstractHelper.uuidToByteArray((UUID) value));
        break;
    case ARRAY:
        throw new UnsupportedOperationException("The saving changes in ARRAY isn't supported.");
        // ps.setArray(position, (Array) value); break; // FIXME the value isn't in type java.sql.Array
    case BYTE_ARRAY:
        if (bd == null || bd.isNull()) {
            ps.setBytes(position, null);
        } else {
            try {
                ps.setBytes(position, IOUtils.toByteArray(bd.getInputStream()));
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
        break;
    case CLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.CLOB);
        } else {
            ps.setClob(position, bd.getReader());
        }
        break;
    case BLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.BLOB);
        } else {
            ps.setBlob(position, bd.getInputStream());
        }
        break;
    case OBJECT:
        ps.setObject(position, value);
    }
}