Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

In this page you can find the example usage for java.sql ResultSet getBytes.

Prototype

byte[] getBytes(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a byte array in the Java programming language.

Usage

From source file:com.kaidad.utilities.MBTilesBase64Converter.java

private static void encodeTileData(final JdbcTemplate c) {
    c.query("SELECT tile_id, tile_data FROM images", new ResultSetExtractor<Object>() {
        @Override//from www  .  j  av a2 s  .  c o  m
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            while (rs.next()) {
                String tileId = rs.getString("tile_id");
                byte[] imageData = rs.getBytes("tile_data");
                addTileDataToStringTable(c, tileId, BaseEncoding.base64().encode(imageData));
            }
            System.out.println("Operation done successfully");
            return null;
        }
    });
}

From source file:org.opoo.oqs.core.mapper.SinglePropertyMapper.java

public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
    Object obj = rs.getObject(index);
    if (obj instanceof Blob) {
        obj = rs.getBytes(index);
    } else if (obj instanceof Clob) {
        obj = rs.getString(index);//from   ww w .j  a  va 2s . c o m
    } else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP")) {
        obj = rs.getTimestamp(index);
    } else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.DATE")) {
        String metaDataClassName = rs.getMetaData().getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj != null && obj instanceof java.sql.Date) {
        if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) {
            obj = rs.getTimestamp(index);
        }
    }
    return obj;
}

From source file:jdbc.JdbcUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the most appropriate
 * value type. The returned value should be a detached value object, not
 * having any ties to the active ResultSet: in particular, it should not be
 * a Blob or Clob object but rather a byte array respectively String
 * representation.//from  ww w .  j a v a  2 s .c om
 * <p>
 * Uses the <code>getObject(index)</code> method, but includes additional
 * "hacks" to get around Oracle 10g returning a non-standard object for its
 * TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
 * leaving out the time portion: These columns will explicitly be extracted
 * as standard <code>java.sql.Timestamp</code> object.
 * 
 * @param rs
 *            is the ResultSet holding the data
 * @param index
 *            is the column index
 * @return the value object
 * @see java.sql.Blob
 * @see java.sql.Clob
 * @see java.sql.Timestamp
 * @see oracle.sql.TIMESTAMP
 */
public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
    Object obj = rs.getObject(index);
    if (obj instanceof Blob) {
        obj = rs.getBytes(index);
    } else if (obj instanceof Clob) {
        obj = rs.getString(index);
    } else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP")) {
        obj = rs.getTimestamp(index);
    } else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.DATE")) {
        String metaDataClassName = rs.getMetaData().getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj != null && obj instanceof Date) {
        if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) {
            obj = rs.getTimestamp(index);
        }
    }
    return obj;
}

From source file:edu.jhu.pha.vospace.jobs.JobsProcessor.java

/**
 * Returns the JobDescription object serialized from the database record
 * @param jobId The identifier of a job/*ww  w.  jav a 2 s  . c  o  m*/
 * @return The job java object
 */
public static JobDescription getJob(final UUID jobId) {
    return DbPoolServlet.goSql("GetJob request", "select json_notation, note from jobs where id = ?",
            new SqlWorker<JobDescription>() {
                @Override
                public JobDescription go(Connection conn, PreparedStatement stmt) throws SQLException {
                    JobDescription returnJob = null;
                    stmt.setString(1, jobId.toString());
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        byte[] jobJsonNotation = rs.getBytes(1);
                        try {
                            returnJob = (new ObjectMapper()).readValue(jobJsonNotation, 0,
                                    jobJsonNotation.length, JobDescription.class);
                            returnJob.setNote(rs.getString("note"));
                        } catch (JsonMappingException ex) { // Shouldn't happen
                            throw new InternalServerErrorException(ex.getMessage());
                        } catch (JsonParseException ex) {
                            throw new InternalServerErrorException(ex.getMessage());
                        } catch (IOException ex) {
                            throw new InternalServerErrorException(ex.getMessage());
                        }
                    }
                    return returnJob;
                }
            });
}

From source file:libepg.util.db.AboutDB.java

/**
 * ???????? ?????//w w  w  . jav  a  2s .  c  o  m
 *
 * @param conn ??DB??
 * @return ?
 * @throws java.sql.SQLException
 * @see libepg.util.db.AboutDB#CRATE_TABLE
 */
public static synchronized List<TsPacket> convertToList(Connection conn) throws SQLException {
    final String DUMP = "SELECT " + PACKET + " FROM " + TABLE_NAME + " ORDER BY number ASC";
    ResultSet rs = conn.createStatement().executeQuery(DUMP);

    //?
    List<TsPacket> packets = new ArrayList<>();
    while (rs.next()) {
        TsPacket tsp = new TsPacket(rs.getBytes(PACKET));
        packets.add(tsp);
    }
    return packets;
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the most appropriate
 * value type. The returned value should be a detached value object, not having
 * any ties to the active ResultSet: in particular, it should not be a Blob or
 * Clob object but rather a byte array respectively String representation.
 * <p>Uses the <code>getObject(index)</code> method, but includes additional "hacks"
 * to get around Oracle 10g returning a non-standard object for its TIMESTAMP
 * datatype and a <code>java.sql.Date</code> for DATE columns leaving out the
 * time portion: These columns will explicitly be extracted as standard
 * <code>java.sql.Timestamp</code> object.
 * @param rs is the ResultSet holding the data
 * @param index is the column index/*  ww w .j  a va 2s  .c o  m*/
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 * @see java.sql.Blob
 * @see java.sql.Clob
 * @see java.sql.Timestamp
 */
public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
    Object obj = rs.getObject(index);
    if (obj instanceof Blob) {
        obj = rs.getBytes(index);
    } else if (obj instanceof Clob) {
        obj = rs.getString(index);
    } else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP")) {
        obj = rs.getTimestamp(index);
    } else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.DATE")) {
        String metaDataClassName = rs.getMetaData().getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj != null && obj instanceof java.sql.Date) {
        if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) {
            obj = rs.getTimestamp(index);
        }
    }
    return obj;
}

From source file:org.geowebcache.sqlite.SqlitlePerf.java

/**
 * Helper method that fetches a tile form the database using the provided connection.
 *//*from w  w w. jav  a  2s.  c o m*/
private static byte[] getTile(Connection connection, long[] xyz) {
    String sql = "SELECT tile_data FROM tiles WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?;";
    try (PreparedStatement statement = connection.prepareStatement(sql)) {
        statement.setLong(1, xyz[2]);
        statement.setLong(2, xyz[0]);
        statement.setLong(3, xyz[1]);
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            // the tile exists
            byte[] data = resultSet.getBytes(1);
            if (data.length != 2024) {
                // the data doesn't have the expected size
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error(String.format("Tile %d-%d-%d data is not valid.", xyz[2], xyz[0], xyz[1]));
                }
            }
            // the tile data looks good
            return data;
        } else {
            // the tile was not found
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(String.format("Failed to load tile %d-%d-%d.", xyz[2], xyz[0], xyz[1]));
            }
            return null;
        }
    } catch (Exception exception) {
        throw Utils.exception(exception, "Error executing SQL '%s'.", sql);
    }
}

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

public static String blobToString(String columnName, String tableName, String whereClause) throws SQLException {
    String str = null;/*from w ww  .  ja  va2s.c o m*/
    if (StringUtils.isNotBlank(whereClause)) {
        Connection conn = DriverManager.getConnection(CURRENT_CONNECTION_URL);
        String sql = "select " + columnName + " from " + tableName + " where " + whereClause;
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            byte[] bytes = null;
            int type = rs.getMetaData().getColumnType(1);
            if (type == Types.BINARY || type == Types.VARBINARY || type == Types.LONGVARBINARY) {
                bytes = rs.getBytes(1);
            } else {
                Blob blob = rs.getBlob(1);
                if (blob != null) {
                    bytes = blob.getBytes(1, MAX_BINARY_LENGTH);
                }
            }
            if (bytes != null) {
                str = new String(Base64.encodeBase64(bytes));
            }
        }
        ps.close();
        conn.close();
    }
    return str == null ? "" : "\"" + str + "\"";
}

From source file:org.snaker.engine.access.jdbc.JdbcHelper.java

/**
 * ??//  ww  w .j a  v  a2 s  . c  o m
 * @param rs
 * @param index
 * @return
 * @throws SQLException
 */
public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
    Object obj = rs.getObject(index);
    String className = null;
    if (obj != null) {
        className = obj.getClass().getName();
    }
    if (obj instanceof Blob) {
        obj = rs.getBytes(index);
    } else if (obj instanceof Clob) {
        obj = rs.getString(index);
    } else if (className != null
            && ("oracle.sql.TIMESTAMP".equals(className) || "oracle.sql.TIMESTAMPTZ".equals(className))) {
        obj = rs.getTimestamp(index);
    } else if (className != null && className.startsWith("oracle.sql.DATE")) {
        String metaDataClassName = rs.getMetaData().getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj != null && obj instanceof java.sql.Date) {
        if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) {
            obj = rs.getTimestamp(index);
        }
    }
    return obj;
}

From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil.java

public static OperationResponse getOperationResponse(ResultSet rs)
        throws ClassNotFoundException, IOException, SQLException {
    OperationResponse response = new OperationResponse();
    if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
        response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
    }//  w  w  w  .jav a  2 s  . co  m
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    byte[] contentBytes;
    try {
        if (rs.getBytes("OPERATION_RESPONSE") != null) {
            contentBytes = (byte[]) rs.getBytes("OPERATION_RESPONSE");
            bais = new ByteArrayInputStream(contentBytes);
            ois = new ObjectInputStream(bais);
            response.setResponse(ois.readObject().toString());
        }
    } finally {
        if (bais != null) {
            try {
                bais.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ByteArrayOutputStream", e);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ObjectOutputStream", e);
            }
        }
    }
    return response;
}