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.springframework.jdbc.object.RdbmsOperation.java

/**
 * Validate the parameters passed to an execute method based on declared parameters.
 * Subclasses should invoke this method before every {@code executeQuery()}
 * or {@code update()} method.//from ww w  .  ja  v a 2  s  .c  o  m
 * @param parameters parameters supplied (may be {@code null})
 * @throws InvalidDataAccessApiUsageException if the parameters are invalid
 */
protected void validateParameters(@Nullable Object[] parameters) throws InvalidDataAccessApiUsageException {
    checkCompiled();
    int declaredInParameters = 0;
    for (SqlParameter param : this.declaredParameters) {
        if (param.isInputValueProvided()) {
            if (!supportsLobParameters()
                    && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
                throw new InvalidDataAccessApiUsageException(
                        "BLOB or CLOB parameters are not allowed for this kind of operation");
            }
            declaredInParameters++;
        }
    }
    validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters);
}

From source file:org.cloudgraph.rdb.filter.RDBStatementExecutor.java

@Override
public void executeInsert(PlasmaType type, StringBuilder sql, Map<String, PropertyPair> values) {
    PreparedStatement statement = null;
    List<InputStream> streams = null;
    try {/*  w w  w.j  av a2s .c  om*/

        if (log.isDebugEnabled()) {
            log.debug("execute: " + sql.toString());
            StringBuilder paramBuf = createParamDebug(values);
            log.debug("params: " + paramBuf.toString());
        }

        statement = con.prepareStatement(sql.toString());

        for (PropertyPair pair : values.values()) {
            PlasmaProperty valueProp = pair.getProp();
            if (pair.getValueProp() != null)
                valueProp = pair.getValueProp();
            int jdbcType = converter.toJDBCDataType(valueProp, pair.getValue());
            Object jdbcValue = converter.toJDBCDataValue(valueProp, pair.getValue());
            if (jdbcType != Types.BLOB && jdbcType != Types.VARBINARY) {
                statement.setObject(pair.getColumn(), jdbcValue, jdbcType);
            } else {
                byte[] bytes = (byte[]) jdbcValue;
                long len = bytes.length;
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                statement.setBinaryStream(pair.getColumn(), is, len);
                if (streams == null)
                    streams = new ArrayList<InputStream>();
                streams.add(is);
            }
        }

        statement.execute();
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        if (streams != null)
            try {
                for (InputStream stream : streams)
                    stream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }

    }
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Get one value into DbValue from ResultSet
 * /*  w w w.j  av a2  s  .co m*/
 * @param rs
 * @param value
 * @throws WaarpDatabaseSqlException
 */
static public void getTrueValue(ResultSet rs, DbValue value) throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.LONGVARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.BIT:
            value.value = rs.getBoolean(value.column);
            break;
        case Types.TINYINT:
            value.value = rs.getByte(value.column);
            break;
        case Types.SMALLINT:
            value.value = rs.getShort(value.column);
            break;
        case Types.INTEGER:
            value.value = rs.getInt(value.column);
            break;
        case Types.BIGINT:
            value.value = rs.getLong(value.column);
            break;
        case Types.REAL:
            value.value = rs.getFloat(value.column);
            break;
        case Types.DOUBLE:
            value.value = rs.getDouble(value.column);
            break;
        case Types.VARBINARY:
            value.value = rs.getBytes(value.column);
            break;
        case Types.DATE:
            value.value = rs.getDate(value.column);
            break;
        case Types.TIMESTAMP:
            value.value = rs.getTimestamp(value.column);
            break;
        case Types.CLOB:
            value.value = rs.getClob(value.column).getCharacterStream();
            break;
        case Types.BLOB:
            value.value = rs.getBlob(value.column).getBinaryStream();
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " for " + value.column);
        }
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Getting values in error: " + value.type + " for " + value.column,
                e);
    }
}

From source file:org.apache.oozie.command.SchemaCheckXCommand.java

private String getSQLTypeFromInt(int t) {
    switch (t) {/*from w  ww  .  j  a v a  2  s  .  co m*/
    case Types.BIT:
        return "BIT";
    case Types.TINYINT:
        return "TINYINT";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT";
    case Types.REAL:
        return "REAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.CHAR:
        return "CHAR";
    case Types.VARCHAR:
        return "VARCHAR";
    case Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case Types.DATE:
        return "DATE";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.BINARY:
        return "BINARY";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NULL:
        return "NULL";
    case Types.OTHER:
        return "OTHER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.DISTINCT:
        return "DISTINCT";
    case Types.STRUCT:
        return "STRUCT";
    case Types.ARRAY:
        return "ARRAY";
    case Types.BLOB:
        return "BLOB";
    case Types.CLOB:
        return "CLOB";
    case Types.REF:
        return "REF";
    case Types.DATALINK:
        return "DATALINK";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.ROWID:
        return "ROWID";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.SQLXML:
        return "SQLXML";
    default:
        return "unknown";
    }
}

From source file:org.springframework.jdbc.object.RdbmsOperation.java

/**
 * Validate the named parameters passed to an execute method based on declared parameters.
 * Subclasses should invoke this method before every {@code executeQuery()} or
 * {@code update()} method./*  w  w  w.  j  a va 2 s.c om*/
 * @param parameters parameter Map supplied (may be {@code null})
 * @throws InvalidDataAccessApiUsageException if the parameters are invalid
 */
protected void validateNamedParameters(@Nullable Map<String, ?> parameters)
        throws InvalidDataAccessApiUsageException {
    checkCompiled();
    Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object>emptyMap());
    int declaredInParameters = 0;
    for (SqlParameter param : this.declaredParameters) {
        if (param.isInputValueProvided()) {
            if (!supportsLobParameters()
                    && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
                throw new InvalidDataAccessApiUsageException(
                        "BLOB or CLOB parameters are not allowed for this kind of operation");
            }
            if (param.getName() != null && !paramsToUse.containsKey(param.getName())) {
                throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName()
                        + "' was not among the parameters supplied: " + paramsToUse.keySet());
            }
            declaredInParameters++;
        }
    }
    validateParameterCount(paramsToUse.size(), declaredInParameters);
}

From source file:org.eclipse.ecr.core.storage.sql.extensions.H2Fulltext.java

protected static String asString(Object data, int type) throws SQLException {
    if (data == null) {
        return "";
    }//from   w w  w . j  a  va2s  .c om
    switch (type) {
    case Types.BIT:
    case DataType.TYPE_BOOLEAN:
    case Types.INTEGER:
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.NUMERIC:
    case Types.REAL:
    case Types.SMALLINT:
    case Types.TINYINT:
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
    case Types.LONGVARCHAR:
    case Types.CHAR:
    case Types.VARCHAR:
        return data.toString();
    case Types.CLOB:
        try {
            if (data instanceof Clob) {
                data = ((Clob) data).getCharacterStream();
            }
            return IOUtils.readStringAndClose((Reader) data, -1);
        } catch (IOException e) {
            throw Message.convert(e);
        }
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
    case Types.BINARY:
    case Types.JAVA_OBJECT:
    case Types.OTHER:
    case Types.BLOB:
    case Types.STRUCT:
    case Types.REF:
    case Types.NULL:
    case Types.ARRAY:
    case DataType.TYPE_DATALINK:
    case Types.DISTINCT:
        throw new SQLException("Unsupported column data type: " + type);
    default:
        return "";
    }
}

From source file:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java

private Object downcastValue(Object value, int dataType) {
    if (value == null) {
        return null;
    }/*from w w w.  j a v a 2s.  c o  m*/
    // Try down casting the value as per its column type.
    try {
        // Some JDBC 4.0 types have been ignored to avoid compilation errors
        switch (dataType) {
        case Types.ARRAY:
            break;
        case Types.BIGINT:
            if (!(value instanceof BigInteger)) {
                value = new BigDecimal(value.toString()).longValue();
            }
            break;
        case Types.BINARY:
            break;
        case Types.BIT:
            if (!(value instanceof Boolean)) {
                value = new Boolean(value.toString());
            }
            break;
        case Types.BLOB:
            break;
        case Types.BOOLEAN:
            if (!(value instanceof Boolean)) {
                value = new Boolean(value.toString());
            }
            break;
        case Types.CHAR:
            break;
        case Types.CLOB:
            break;
        case Types.DATALINK:
            break;
        case Types.DATE:
            break;
        case Types.DECIMAL:
            //ODE-872: Oracle 9g and 10g has problems with BigDecimal on Java1.5
            value = new BigDecimal(new BigDecimal(value.toString()).toPlainString());
            break;
        case Types.DISTINCT:
            break;
        case Types.DOUBLE:
            if (!(value instanceof Double)) {
                value = Double.valueOf(value.toString()).doubleValue();
            }
            break;
        case Types.FLOAT:
            if (!(value instanceof Float)) {
                value = Float.valueOf(value.toString()).floatValue();
            }
            break;
        case Types.INTEGER:
            if (!(value instanceof Integer)) {
                value = Double.valueOf(value.toString()).intValue();
            }
            break;
        case Types.JAVA_OBJECT:
            break;
        //          case Types.LONGNVARCHAR:
        //             break;
        case Types.LONGVARBINARY:
            break;
        case Types.LONGVARCHAR:
            break;
        //          case Types.NCHAR:
        //             break;
        //          case Types.NCLOB:
        //             break;
        case Types.NUMERIC:
            //ODE-872: Oracle 9g and 10g has problems with BigDecimal on Java1.5
            value = new BigDecimal(new BigDecimal(value.toString()).toPlainString());
            break;
        //          case Types.NVARCHAR:
        //             break;
        case Types.OTHER:
            break;
        case Types.REAL:
            if (!(value instanceof Double)) {
                value = Float.valueOf(value.toString()).floatValue();
            }
            break;
        case Types.REF:
            break;
        //          case Types.ROWID:
        //             break;
        case Types.SMALLINT:
            if (!(value instanceof Short)) {
                value = new Short(value.toString()).shortValue();
            }
            break;
        //          case Types.SQLXML:
        //             break;
        case Types.STRUCT:
            break;
        case Types.TIME:
            break;
        case Types.TIMESTAMP:
            break;
        case Types.TINYINT:
            if (!(value instanceof Short)) {
                value = new Short(value.toString()).shortValue();
            }
            break;
        case Types.VARBINARY:
            break;
        case Types.VARCHAR:
            break;
        default:
            break;
        }
    } catch (Exception e) {
        // couldn't cast... let's just use original value object
    }
    return value;
}

From source file:org.jumpmind.metl.core.runtime.component.DataDiff.java

protected void createDatabase() {
    if (databasePlatform == null) {
        ResettableBasicDataSource ds = new ResettableBasicDataSource();
        ds.setDriverClassName(Driver.class.getName());
        ds.setMaxActive(1);/*from  www  .  ja  v a 2s . c  om*/
        ds.setInitialSize(1);
        ds.setMinIdle(1);
        ds.setMaxIdle(1);
        databaseName = UUID.randomUUID().toString();
        if (inMemoryCompare) {
            ds.setUrl("jdbc:h2:mem:" + databaseName);
        } else {
            ds.setUrl("jdbc:h2:file:./" + databaseName);
        }
        databasePlatform = JdbcDatabasePlatformFactory.createNewPlatformInstance(ds, new SqlTemplateSettings(),
                true, false);

        Model inputModel = context.getFlowStep().getComponent().getInputModel();
        List<ModelEntity> entities = inputModel.getModelEntities();
        for (ModelEntity entity : entities) {
            Table table = new Table();
            table.setName(entity.getName() + "_1");
            List<ModelAttribute> attributes = entity.getModelAttributes();
            for (ModelAttribute attribute : attributes) {
                DataType dataType = attribute.getDataType();
                Column column = new Column(attribute.getName());
                if (dataType.isNumeric()) {
                    column.setTypeCode(Types.DECIMAL);
                } else if (dataType.isBoolean()) {
                    column.setTypeCode(Types.BOOLEAN);
                } else if (dataType.isTimestamp()) {
                    column.setTypeCode(Types.TIMESTAMP);
                } else if (dataType.isBinary()) {
                    column.setTypeCode(Types.BLOB);
                } else {
                    column.setTypeCode(Types.LONGVARCHAR);
                }

                column.setPrimaryKey(attribute.isPk());
                table.addColumn(column);
            }
            alterCaseToMatchLogicalCase(table);
            databasePlatform.createTables(false, false, table);

            table.setName(entity.getName().toUpperCase() + "_2");
            databasePlatform.createTables(false, false, table);

        }

        log(LogLevel.INFO, "Creating databasePlatform with the following url: %s", ds.getUrl());
    }
}

From source file:org.apache.kylin.common.persistence.JDBCResourceDAO.java

public void checkAndPutResource(final String resPath, final byte[] content, final long oldTS, final long newTS)
        throws SQLException, WriteConflictException {
    logger.trace(//from  w w w  .  j a  v  a  2 s .co  m
            "execute checkAndPutResource method. resPath : {} , oldTs : {} , newTs : {} , content null ? : {} ",
            resPath, oldTS, newTS, content == null);
    executeSql(new SqlOperation() {
        @Override
        public void execute(Connection connection) throws SQLException {
            synchronized (resPath.intern()) {
                String tableName = getMetaTableName(resPath);
                if (!existResource(resPath)) {
                    if (oldTS != 0) {
                        throw new IllegalStateException(
                                "For not exist file. OldTS have to be 0. but Actual oldTS is : " + oldTS);
                    }
                    if (isContentOverflow(content, resPath)) {
                        logger.debug("Overflow! resource path: {}, content size: {}", resPath, content.length);
                        pstat = connection.prepareStatement(getInsertSqlWithoutContent(tableName));
                        pstat.setString(1, resPath);
                        pstat.setLong(2, newTS);
                        writeLargeCellToHdfs(resPath, content);
                        try {
                            int result = pstat.executeUpdate();
                            if (result != 1)
                                throw new SQLException();
                        } catch (SQLException e) {
                            rollbackLargeCellFromHdfs(resPath);
                            throw e;
                        }
                    } else {
                        pstat = connection.prepareStatement(getInsertSql(tableName));
                        pstat.setString(1, resPath);
                        pstat.setLong(2, newTS);
                        pstat.setBlob(3, new BufferedInputStream(new ByteArrayInputStream(content)));
                        pstat.executeUpdate();
                    }
                } else {
                    // Note the checkAndPut trick:
                    // update {0} set {1}=? where {2}=? and {3}=?
                    pstat = connection.prepareStatement(getUpdateSqlWithoutContent(tableName));
                    pstat.setLong(1, newTS);
                    pstat.setString(2, resPath);
                    pstat.setLong(3, oldTS);
                    int result = pstat.executeUpdate();
                    if (result != 1) {
                        long realTime = getResourceTimestamp(resPath);
                        throw new WriteConflictException("Overwriting conflict " + resPath + ", expect old TS "
                                + oldTS + ", but it is " + realTime);
                    }
                    PreparedStatement pstat2 = null;
                    try {
                        // "update {0} set {1}=? where {3}=?"
                        pstat2 = connection.prepareStatement(getUpdateContentSql(tableName));
                        if (isContentOverflow(content, resPath)) {
                            logger.debug("Overflow! resource path: {}, content size: {}", resPath,
                                    content.length);
                            pstat2.setNull(1, Types.BLOB);
                            pstat2.setString(2, resPath);
                            writeLargeCellToHdfs(resPath, content);
                            try {
                                int result2 = pstat2.executeUpdate();
                                if (result2 != 1)
                                    throw new SQLException();
                            } catch (SQLException e) {
                                rollbackLargeCellFromHdfs(resPath);
                                throw e;
                            }
                            cleanOldLargeCellFromHdfs(resPath);
                        } else {
                            pstat2.setBinaryStream(1,
                                    new BufferedInputStream(new ByteArrayInputStream(content)));
                            pstat2.setString(2, resPath);
                            pstat2.executeUpdate();
                        }
                    } finally {
                        JDBCConnectionManager.closeQuietly(pstat2);
                    }
                }
            }
        }
    });
}

From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java

protected Object getObjectValue(String value, Column column, BinaryEncoding encoding, boolean useVariableDates,
        boolean fitToColumn) throws DecoderException {
    Object objectValue = value;/*from  ww  w  .  j av a2 s  .c  o  m*/
    int type = column.getMappedTypeCode();
    if ((value == null || (getDdlBuilder().getDatabaseInfo().isEmptyStringNulled() && value.equals("")))
            && column.isRequired() && column.isOfTextType()) {
        objectValue = REQUIRED_FIELD_NULL_SUBSTITUTE;
    }
    if (value != null) {
        if (type == Types.DATE || type == Types.TIMESTAMP || type == Types.TIME) {
            objectValue = parseDate(type, value, useVariableDates);
        } else if (type == Types.CHAR) {
            String charValue = value.toString();
            if ((StringUtils.isBlank(charValue)
                    && getDdlBuilder().getDatabaseInfo().isBlankCharColumnSpacePadded())
                    || (StringUtils.isNotBlank(charValue)
                            && getDdlBuilder().getDatabaseInfo().isNonBlankCharColumnSpacePadded())) {
                objectValue = StringUtils.rightPad(value.toString(), column.getSizeAsInt(), ' ');
            }
        } else if (type == Types.BIGINT) {
            objectValue = parseBigInteger(value);
        } else if (type == Types.INTEGER || type == Types.SMALLINT || type == Types.BIT
                || type == Types.TINYINT) {
            objectValue = parseInteger(value);
        } else if (type == Types.NUMERIC || type == Types.DECIMAL || type == Types.FLOAT || type == Types.DOUBLE
                || type == Types.REAL) {
            objectValue = parseBigDecimal(value);
        } else if (type == Types.BOOLEAN) {
            objectValue = value.equals("1") ? Boolean.TRUE : Boolean.FALSE;
        } else if (!(column.getJdbcTypeName() != null
                && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOMETRY))
                && !(column.getJdbcTypeName() != null
                        && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOGRAPHY))
                && (type == Types.BLOB || type == Types.LONGVARBINARY || type == Types.BINARY
                        || type == Types.VARBINARY ||
                        // SQLServer ntext type
                        type == -10)) {
            if (encoding == BinaryEncoding.NONE) {
                objectValue = value.getBytes();
            } else if (encoding == BinaryEncoding.BASE64) {
                objectValue = Base64.decodeBase64(value.getBytes());
            } else if (encoding == BinaryEncoding.HEX) {
                objectValue = Hex.decodeHex(value.toCharArray());
            }
        } else if (type == Types.ARRAY) {
            objectValue = createArray(column, value);
        }
    }
    if (objectValue instanceof String) {
        String stringValue = cleanTextForTextBasedColumns((String) objectValue);
        int size = column.getSizeAsInt();
        if (fitToColumn && size > 0 && stringValue.length() > size) {
            stringValue = stringValue.substring(0, size);
        }
        objectValue = stringValue;
    }

    return objectValue;

}