Example usage for java.sql Types BLOB

List of usage examples for java.sql Types BLOB

Introduction

In this page you can find the example usage for java.sql Types BLOB.

Prototype

int BLOB

To view the source code for java.sql Types BLOB.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type BLOB.

Usage

From source file:org.apache.ddlutils.platform.postgresql.PostgreSqlPlatform.java

/**
 * {@inheritDoc}//  ww w.java2s.c o m
 */
protected void setObject(PreparedStatement statement, int sqlIndex, DynaBean dynaBean, SqlDynaProperty property)
        throws SQLException {
    int typeCode = property.getColumn().getTypeCode();
    Object value = dynaBean.get(property.getName());

    // PostgreSQL doesn't like setNull for BYTEA columns
    if (value == null) {
        switch (typeCode) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
        case Types.BLOB:
            statement.setBytes(sqlIndex, null);
            break;
        default:
            statement.setNull(sqlIndex, typeCode);
            break;
        }
    } else {
        super.setObject(statement, sqlIndex, dynaBean, property);
    }
}

From source file:madgik.exareme.master.queryProcessor.analyzer.stat.ExternalStat.java

private int computeColumnSize(String columnName, int columnType, String table_sample) throws Exception {
    int columnSize = 0;
    if (columnType == Types.INTEGER || columnType == Types.REAL || columnType == Types.DOUBLE
            || columnType == Types.DECIMAL || columnType == Types.FLOAT || columnType == Types.NUMERIC) {
        columnSize = NUM_SIZE;// ww  w.j  a va2  s . co m
    } else if (columnType == Types.VARCHAR) {
        String query0 = "select max(length(" + columnName + ")) as length from (select " + columnName + " from "
                + table_sample + ") A" + " where " + columnName + " is not null limit " + MAX_STRING_SAMPLE;

        if (con.getClass().getName().contains("oracle")) {
            query0 = "select max(length(" + columnName + ")) as length from (select " + columnName + " from "
                    + table_sample + ") A" + " where " + columnName + " is not null and ROWNUM< "
                    + MAX_STRING_SAMPLE;
        }
        log.debug("executing col size query:" + query0);
        Statement stmt0 = con.createStatement();
        ResultSet rs0 = stmt0.executeQuery(query0);

        while (rs0.next()) {
            columnSize = rs0.getInt("length");
        }
        rs0.close();
        stmt0.close();

    } else if (columnType == Types.BLOB)
        columnSize = BLOB_SIZE;

    return columnSize;
}

From source file:com.opengamma.masterdb.exchange.DbExchangeMaster.java

/**
 * Inserts a new document.//ww  w . jav  a  2  s  . co m
 * 
 * @param document  the document, not null
 * @return the new document, not null
 */
@Override
protected ExchangeDocument insert(final ExchangeDocument document) {
    ArgumentChecker.notNull(document.getExchange(), "document.exchange");
    ArgumentChecker.notNull(document.getName(), "document.name");

    final ManageableExchange exchange = document.getExchange();
    final long docId = nextId("exg_exchange_seq");
    final long docOid = (document.getUniqueId() != null ? extractOid(document.getUniqueId()) : docId);
    // set the uniqueId (needs to go in Fudge message)
    final UniqueId uniqueId = createUniqueId(docOid, docId);
    exchange.setUniqueId(uniqueId);
    document.setUniqueId(uniqueId);
    // the arguments for inserting into the exchange table
    FudgeMsgEnvelope env = FUDGE_CONTEXT.toFudgeMsg(exchange);
    byte[] bytes = FUDGE_CONTEXT.toByteArray(env.getMessage());
    final DbMapSqlParameterSource docArgs = new DbMapSqlParameterSource().addValue("doc_id", docId)
            .addValue("doc_oid", docOid).addTimestamp("ver_from_instant", document.getVersionFromInstant())
            .addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
            .addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
            .addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
            .addValue("name", document.getName())
            .addValue("time_zone", exchange.getTimeZone() != null ? exchange.getTimeZone().getId() : null,
                    Types.VARCHAR)
            .addValue("detail", new SqlLobValue(bytes, getDialect().getLobHandler()), Types.BLOB);
    // the arguments for inserting into the idkey tables
    final List<DbMapSqlParameterSource> assocList = new ArrayList<DbMapSqlParameterSource>();
    final List<DbMapSqlParameterSource> idKeyList = new ArrayList<DbMapSqlParameterSource>();
    final String sqlSelectIdKey = getElSqlBundle().getSql("SelectIdKey");
    for (ExternalId id : exchange.getExternalIdBundle()) {
        final DbMapSqlParameterSource assocArgs = new DbMapSqlParameterSource().addValue("doc_id", docId)
                .addValue("key_scheme", id.getScheme().getName()).addValue("key_value", id.getValue());
        assocList.add(assocArgs);
        if (getJdbcTemplate().queryForList(sqlSelectIdKey, assocArgs).isEmpty()) {
            // select avoids creating unecessary id, but id may still not be used
            final long idKeyId = nextId("exg_idkey_seq");
            final DbMapSqlParameterSource idkeyArgs = new DbMapSqlParameterSource()
                    .addValue("idkey_id", idKeyId).addValue("key_scheme", id.getScheme().getName())
                    .addValue("key_value", id.getValue());
            idKeyList.add(idkeyArgs);
        }
    }
    final String sqlDoc = getElSqlBundle().getSql("Insert", docArgs);
    final String sqlIdKey = getElSqlBundle().getSql("InsertIdKey");
    final String sqlDoc2IdKey = getElSqlBundle().getSql("InsertDoc2IdKey");
    getJdbcTemplate().update(sqlDoc, docArgs);
    getJdbcTemplate().batchUpdate(sqlIdKey, idKeyList.toArray(new DbMapSqlParameterSource[idKeyList.size()]));
    getJdbcTemplate().batchUpdate(sqlDoc2IdKey,
            assocList.toArray(new DbMapSqlParameterSource[assocList.size()]));
    return document;
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Map JDBC objects to Java equivalents.
 * Used by getBean() and getBeans().//  w  ww.  j  av  a  2s.  c  o  m
 * <p>
 * Some types not supported.
 * Many not work with all drivers.
 * <p>
 * Makes binary conversions of BIGINT, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER,
 * REAL, SMALLINT, TIME, TIMESTAMP, TINYINT.
 * Makes Sting conversions of CHAR, CLOB, VARCHAR, LONGVARCHAR, BLOB, LONGVARBINARY,
 * VARBINARY.
 * <p>
 * DECIMAL, INTEGER, SMALLINT, TIMESTAMP, CHAR, VARCHAR tested with MySQL and Poolman.
 * Others not guaranteed.
 * @param classeDestino 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 */
private static void putEntry(Map properties, ResultSetMetaData metaData, ResultSet resultSet, int i,
        Class classeDestino) throws Exception {

    /*
    In a perfect universe, this would be enough
    properties.put(
        metaData.getColumnName(i),
        resultSet.getObject(i));
    But only String, Timestamp, and Integer seem to get through that way.
    */

    String columnName = metaData.getColumnName(i);

    // Testa se  uma FK
    /*Field[] fields = classeDestino.getDeclaredFields();
    for (int j = 0; j < fields.length; j++) {
    if (fields[j].getAnnotation(DBFK.class) != null) {
        properties.put(columnName, resultSet.getString(i));
    }
    }*/
    //System.out.println(i+"-"+metaData.getColumnType(i));
    switch (metaData.getColumnType(i)) {

    // http://java.sun.com/j2se/1.3.0/docs/api/java/sql/Types.html

    case Types.BIGINT:
        properties.put(columnName, new Long(resultSet.getLong(i)));
        break;

    case Types.DATE:
        properties.put(columnName, resultSet.getDate(i));
        break;

    case Types.DECIMAL:
    case Types.DOUBLE:
        properties.put(columnName, new Double(resultSet.getDouble(i)));
        break;

    case Types.FLOAT:
        properties.put(columnName, new Float(resultSet.getFloat(i)));
        break;

    case Types.INTEGER:
        int valor = 0;
        try { // Se o campo esta vazio d erro
            valor = resultSet.getInt(i);
        } catch (SQLException e) {
        }
        properties.put(columnName, new Integer(valor));
        break;

    case Types.REAL:
        properties.put(columnName, new Double(resultSet.getString(i)));
        break;

    case Types.SMALLINT:
        properties.put(columnName, new Short(resultSet.getShort(i)));
        break;

    case Types.TIME:
        properties.put(columnName, resultSet.getTime(i));
        break;

    case Types.TIMESTAMP:
        properties.put(columnName, resultSet.getTimestamp(i));
        break;

    // :FIXME: Throws java.lang.ClassCastException: java.lang.Integer
    // :FIXME: with Poolman and MySQL unless use getString.
    case Types.TINYINT:
        properties.put(columnName, new Byte(resultSet.getString(i)));
        break;

    case Types.CHAR:
    case Types.CLOB:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        // :FIXME: Handle binaries differently?
    case Types.BLOB:
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
        properties.put(columnName, resultSet.getString(i));
        break;

    /*
        :FIXME: Add handlers for
        ARRAY
        BINARY
        BIT
        DISTINCT
        JAVA_OBJECT
        NULL
        NUMERIC
        OTHER
        REF
        STRUCT
    */

    // Otherwise, pass as *String property to be converted
    default:
        properties.put(columnName + "String", resultSet.getString(i));
        break;
    } // end switch

}

From source file:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Dump a generic table to XML//  w  ww  . j  a v  a2s . com
 *
 * @param tableName     name of the table
 * @param stmt          an open statement
 * @param out           output stream
 * @param sb            an available and valid StringBuilder
 * @param xmlTag        name of the xml tag to write per row
 * @param idColumn      (optional) id column to sort results
 * @param onlyBinaries  process binary fields (else these will be ignored)
 * @throws SQLException on errors
 * @throws IOException  on errors
 */
private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag,
        String idColumn, boolean onlyBinaries) throws SQLException, IOException {
    ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName
            + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC"));
    final ResultSetMetaData md = rs.getMetaData();
    String value, att;
    boolean hasSubTags;
    while (rs.next()) {
        hasSubTags = false;
        if (!onlyBinaries) {
            sb.setLength(0);
            sb.append("  <").append(xmlTag);
        }
        for (int i = 1; i <= md.getColumnCount(); i++) {
            value = null;
            att = md.getColumnName(i).toLowerCase();
            switch (md.getColumnType(i)) {
            case java.sql.Types.DECIMAL:
            case java.sql.Types.NUMERIC:
            case java.sql.Types.BIGINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getBigDecimal(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.INTEGER:
            case java.sql.Types.SMALLINT:
            case java.sql.Types.TINYINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getLong(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.DOUBLE:
            case java.sql.Types.FLOAT:
            case java.sql.Types.REAL:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getDouble(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.TIMESTAMP:
            case java.sql.Types.DATE:
                if (!onlyBinaries) {
                    final Timestamp ts = rs.getTimestamp(i);
                    if (rs.wasNull())
                        value = null;
                    else
                        value = FxFormatUtils.getDateTimeFormat().format(ts);
                }
                break;
            case java.sql.Types.BIT:
            case java.sql.Types.CHAR:
            case java.sql.Types.BOOLEAN:
                if (!onlyBinaries) {
                    value = rs.getBoolean(i) ? "1" : "0";
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.CLOB:
            case java.sql.Types.BLOB:
            case java.sql.Types.LONGVARBINARY:
            case java.sql.Types.LONGVARCHAR:
            case java.sql.Types.VARBINARY:
            case java.sql.Types.VARCHAR:
            case java.sql.Types.BINARY:
            case SQL_LONGNVARCHAR:
            case SQL_NCHAR:
            case SQL_NCLOB:
            case SQL_NVARCHAR:

                hasSubTags = true;
                break;
            default:
                LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]");
            }
            if (value != null && !onlyBinaries)
                sb.append(' ').append(att).append("=\"").append(value).append("\"");
        }
        if (hasSubTags) {
            if (!onlyBinaries)
                sb.append(">\n");
            for (int i = 1; i <= md.getColumnCount(); i++) {
                switch (md.getColumnType(i)) {
                case java.sql.Types.VARBINARY:
                case java.sql.Types.LONGVARBINARY:
                case java.sql.Types.BLOB:
                case java.sql.Types.BINARY:
                    if (idColumn == null)
                        throw new IllegalArgumentException("Id column required to process binaries!");
                    String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i
                            + ".blob";
                    att = md.getColumnName(i).toLowerCase();
                    if (onlyBinaries) {
                        if (!(out instanceof ZipOutputStream))
                            throw new IllegalArgumentException(
                                    "out has to be a ZipOutputStream to store binaries!");
                        ZipOutputStream zip = (ZipOutputStream) out;
                        InputStream in = rs.getBinaryStream(i);
                        if (rs.wasNull())
                            break;

                        ZipEntry ze = new ZipEntry(binFile);
                        zip.putNextEntry(ze);

                        byte[] buffer = new byte[4096];
                        int read;
                        while ((read = in.read(buffer)) != -1)
                            zip.write(buffer, 0, read);
                        in.close();
                        zip.closeEntry();
                        zip.flush();
                    } else {
                        InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty
                        if (rs.wasNull())
                            break;
                        in.close();
                        sb.append("    <").append(att).append(">").append(binFile).append("</").append(att)
                                .append(">\n");
                    }
                    break;
                case java.sql.Types.CLOB:
                case SQL_LONGNVARCHAR:
                case SQL_NCHAR:
                case SQL_NCLOB:
                case SQL_NVARCHAR:
                case java.sql.Types.LONGVARCHAR:
                case java.sql.Types.VARCHAR:
                    if (!onlyBinaries) {
                        value = rs.getString(i);
                        if (rs.wasNull())
                            break;
                        att = md.getColumnName(i).toLowerCase();
                        sb.append("    <").append(att).append('>');
                        escape(sb, value);
                        sb.append("</").append(att).append(">\n");
                    }
                    break;
                }
            }
            if (!onlyBinaries)
                sb.append("  </").append(xmlTag).append(">\n");
        } else {
            if (!onlyBinaries)
                sb.append("/>\n");
        }
        if (!onlyBinaries)
            write(out, sb);
    }
}

From source file:org.apache.camel.processor.aggregate.jdbc.OptimisticLockingJdbcAggregationRepository.java

@Override
public void remove(CamelContext camelContext, String key, Exchange exchange) {
    getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override//  w  w  w  . j  a v  a  2 s.  c o  m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                log.debug(String.format("Removing key [%s]", key));

                String confirmKey = exchange.getExchangeId();
                long version = exchange.getProperty(VERSION_EXCHANGE_PROPERTY, Long.class);
                byte[] marshalledExchange = getCodec().marshallExchange(camelContext, exchange, true);

                getJdbcTemplate().update(
                        String.format("DELETE FROM %1$s WHERE %2$s = ? AND %3$s = ?", getRepositoryName(),
                                ID_KEY, VERSION_KEY),
                        new Object[] { key, version }, new int[] { Types.VARCHAR, Types.BIGINT });

                getJdbcTemplate().update(
                        String.format("INSERT INTO %1$s (%2$s, %3$s, %4$s) VALUES (?, ?, ?)",
                                getRepositoryNameCompleted(), ID_KEY, EXCHANGE_KEY, VERSION_KEY),
                        new Object[] { confirmKey, new SqlLobValue(marshalledExchange, getLobHandler()), 1L },
                        new int[] { Types.VARCHAR, Types.BLOB, Types.BIGINT });
            } catch (Exception e) {
                throw new RuntimeException(
                        String.format("Error removing key [%s] from repository [%s]", key, getRepositoryName()),
                        e);
            }
        }
    });
}

From source file:org.globus.workspace.persistence.PersistenceAdapterImpl.java

public void setState(int id, int state, Throwable t) throws WorkspaceDatabaseException {

    if (this.dbTrace) {
        logger.trace("setState(): " + Lager.id(id) + ", state = " + state);
    }//from   www . j a  va 2s  .  co  m

    final byte[] faultBytes;

    try {
        faultBytes = ErrorUtil.toByteArray(t);
    } catch (IOException e) {
        throw new WorkspaceDatabaseException(e);
    }

    Connection c = null;
    PreparedStatement pstmt = null;
    try {
        c = getConnection();
        pstmt = c.prepareStatement(SQL_SET_STATE);
        pstmt.setInt(1, state);
        if (faultBytes != null) {
            pstmt.setObject(2, faultBytes, Types.BLOB);
        } else {
            pstmt.setNull(2, Types.BLOB);
        }
        pstmt.setInt(3, id);
        final int updated = pstmt.executeUpdate();

        if (this.dbTrace) {
            logger.trace(Lager.id(id) + ": updated " + updated + " rows");
        }

    } catch (SQLException e) {
        logger.error("", e);
        throw new WorkspaceDatabaseException(e);
    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
            if (c != null) {
                returnConnection(c);
            }
        } catch (SQLException sql) {
            logger.error("SQLException in finally cleanup", sql);
        }
    }
}

From source file:org.jumpmind.symmetric.db.derby.DerbyFunctions.java

public static String getPrimaryKeyWhereString(String[] pkColumnNames, ResultSet rs) throws SQLException {
    final String AND = " and ";
    ResultSetMetaData metaData = rs.getMetaData();
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < pkColumnNames.length; i++) {
        String columnName = pkColumnNames[i];
        int index = findColumnIndex(metaData, columnName);
        int type = metaData.getColumnType(index);
        if (type != Types.BINARY && type != Types.BLOB && type != Types.LONGVARBINARY
                && type != Types.VARBINARY) {
            b.append("\"").append(columnName).append("\"=");
            switch (type) {
            case Types.BIT:
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.INTEGER:
            case Types.BIGINT:
            case Types.FLOAT:
            case Types.REAL:
            case Types.DOUBLE:
            case Types.NUMERIC:
            case Types.DECIMAL:
            case Types.BOOLEAN:
                b.append(rs.getObject(index));
                break;
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                b.append("\"").append(rs.getString(index)).append("\"");
                break;
            case Types.DATE:
            case Types.TIMESTAMP:
                b.append("{ts '");
                b.append(rs.getString(index));
                b.append("'}");
                break;
            }//from w  w w  .ja v a 2  s  . co m
            b.append(AND);
        }
    }
    b.replace(b.length() - AND.length(), b.length(), "");
    return b.toString();
}

From source file:com.squid.core.domain.operators.ExtendedType.java

private String getTypeName(int SQLType) {
    switch (SQLType) {
    case Types.ARRAY:
        return "ARRAY";
    case Types.BIGINT:
        return "INTEGER";
    case Types.BINARY:
        return "BINARY";
    case Types.BIT:
        return "BIT";
    case Types.BLOB:
        return "BLOB";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.CHAR:
        return "CHAR";
    case Types.CLOB:
        return "CLOB";
    case Types.DATALINK:
        return "DATALINK";
    case Types.DATE:
        return "DATE";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.FLOAT:
        return "FLOAT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.NULL:
        return "UNDEFINED";//
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.OTHER:
        return "UNDEFINED";//
    case Types.REAL:
        return "REAL";
    case Types.REF:
        return "REF";
    case Types.ROWID:
        return "ROWID";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.SQLXML:
        return "SQLXML";
    case Types.STRUCT:
        return "STRUCT";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.TINYINT:
        return "TINYINT";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.VARCHAR:
        return "VARCHAR";
    default://from  www .  j  a va2  s .co  m
        return "UNDEFINED";//
    }
}

From source file:org.apache.cayenne.unit.di.server.SchemaBuilder.java

private void dbEntitiesFilter(List<DbEntity> entities) {
    // filter various unsupported tests...

    // LOBs/* w  w  w.j ava 2s.c  om*/
    boolean excludeLOB = !unitDbAdapter.supportsLobs();
    boolean excludeBinPK = !unitDbAdapter.supportsBinaryPK();
    if (excludeLOB || excludeBinPK) {

        List<DbEntity> filtered = new ArrayList<DbEntity>();

        for (DbEntity ent : entities) {

            // check for LOB attributes
            if (excludeLOB) {
                if (Arrays.binarySearch(EXTRA_EXCLUDED_FOR_NO_LOB, ent.getName()) >= 0) {
                    continue;
                }

                boolean hasLob = false;
                for (final DbAttribute attr : ent.getAttributes()) {
                    if (attr.getType() == Types.BLOB || attr.getType() == Types.CLOB) {
                        hasLob = true;
                        break;
                    }
                }

                if (hasLob) {
                    continue;
                }
            }

            // check for BIN PK
            if (excludeBinPK) {
                boolean skip = false;
                for (final DbAttribute attr : ent.getAttributes()) {
                    // check for BIN PK or FK to BIN Pk
                    if (attr.getType() == Types.BINARY || attr.getType() == Types.VARBINARY
                            || attr.getType() == Types.LONGVARBINARY) {

                        if (attr.isPrimaryKey() || attr.isForeignKey()) {
                            skip = true;
                            break;
                        }
                    }
                }

                if (skip) {
                    continue;
                }
            }

            filtered.add(ent);
        }

        entities = filtered;
    }
}