Example usage for java.sql ResultSet getBlob

List of usage examples for java.sql ResultSet getBlob

Introduction

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

Prototype

Blob getBlob(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:Main.java

public static byte[] getBLOB(int id, Connection conn) throws Exception {
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    String query = "SELECT photo FROM MyPictures WHERE id = ?";
    try {//from   w  w w  . j a  v a  2 s .co  m
        pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        Blob blob = rs.getBlob(3);
        // materialize BLOB onto client
        return blob.getBytes(1, (int) blob.length());
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}

From source file:org.etudes.jforum.dao.oracle.OracleUtils.java

public static String readBlobUTF16BinaryStream(ResultSet rs, String fieldName)
        throws IOException, SQLException {
    Blob clob = rs.getBlob(fieldName);

    InputStream is = clob.getBinaryStream();
    StringBuffer sb = new StringBuffer();
    int readedBytes = 0;
    int bufferSize = 4096;

    do {/*  w  w w.  j  av a 2s. c  o m*/
        byte[] bytes = new byte[bufferSize];
        readedBytes = is.read(bytes);
        if (readedBytes > 0) {
            String readed = new String(bytes, 0, readedBytes, "UTF-16");
            sb.append(readed);
        }
    } while (readedBytes == bufferSize);

    is.close();

    return sb.toString();
}

From source file:Main.java

public static byte[] getBLOB(int id, Connection conn) throws Exception {
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    String query = "SELECT photo FROM MyPictures WHERE id = ?";
    try {/* ww  w .java2s .  co m*/
        pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        Blob blob = rs.getBlob("photo");
        // materialize BLOB onto client
        return blob.getBytes(1, (int) blob.length());
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}

From source file:com.espertech.esperio.db.core.DBUtil.java

/**
 * Returns the object value for a given column and type.
 * @param rs result set/*from   ww  w . j a  va 2s  .com*/
 * @param index column index
 * @param valueType value type
 * @return object value
 * @throws java.sql.SQLException if the column could not be read
 */
public static Object getValue(ResultSet rs, int index, int valueType) throws SQLException {
    if (valueType == Types.INTEGER) {
        return rs.getInt(index);
    } else if (valueType == Types.BIGINT) {
        return rs.getLong(index);
    } else if (valueType == Types.BLOB) {
        Blob blob = rs.getBlob(index);
        return getBlobValue(blob);
    }
    return rs.getObject(index);
}

From source file:FacultyAdvisement.StudentRepository.java

public static String getPicture(DataSource ds, String key) throws SQLException {

    Blob image = null;//w ww. j a v a  2  s.  co m

    Connection conn = ds.getConnection();
    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }
    try {
        PreparedStatement ps = conn.prepareStatement("SELECT * FROM USERTABLE WHERE USERNAME = ?");
        ps.setString(1, key);
        ResultSet result = ps.executeQuery();
        while (result.next()) {
            image = result.getBlob("IMAGE");
        }
    } finally {
        conn.close();
    }

    if (image != null) {
        return "ImageServlet?username=" + key;
    } else {
        return "/resources/default-image.png";
    }
}

From source file:org.opencms.db.oracle.CmsUserDriver.java

/**
 * Generates an Output stream that writes to a blob, also truncating the existing blob if required.<p>
 * // w w  w.  ja  v a  2 s. c  o  m
 * Apparently Oracle requires some non-standard handling here.<p>
 * 
 * @param res the result set where the blob is located in 
 * @param name the name of the database column where the blob is located
 * @return an Output stream from a blob
 * @throws SQLException if something goes wring
 */
@SuppressWarnings("deprecation")
public static OutputStream getOutputStreamFromBlob(ResultSet res, String name) throws SQLException {

    // TODO: perform blob check only once and store Oracle version in a static private member 
    // TODO: best do this during system startup / db init phase once
    Blob blob = res.getBlob(name);
    try {
        // jdbc standard
        blob.truncate(0);
        return blob.setBinaryStream(0L);
    } catch (SQLException e) {
        // oracle 9 & 8 (if using the same jdbc driver as provided by oracle9: ojdbc14.jar)
        ((oracle.sql.BLOB) blob).trim(0);
        return ((oracle.sql.BLOB) blob).getBinaryOutputStream();
    }
}

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  ww  w.j  a va 2s .  com*/
    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:com.trackplus.ddl.DataReader.java

private static int getBlobTableData(BufferedWriter writer, Connection connection) throws DDLException {
    try {/*from  w ww .  j  a va2s  .c  o m*/
        Statement st = connection.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM TBLOB");
        int idx = 0;
        while (rs.next()) {
            StringBuilder line = new StringBuilder();

            //OBJECTID
            String value = rs.getString("OBJECTID");
            line.append(value).append(",");

            //BLOBVALUE
            Blob blobValue = rs.getBlob("BLOBVALUE");
            if (blobValue != null) {
                String str = new String(Base64.encodeBase64(blobValue.getBytes(1l, (int) blobValue.length())));
                if (str.length() == 0) {
                    str = " ";
                }
                line.append(str);
            } else {
                line.append("null");
            }
            line.append(",");

            //TPUUID
            value = rs.getString("TPUUID");
            line.append(value);
            writer.write(line.toString());
            writer.newLine();
            idx++;
        }
        rs.close();
        return idx;
    } catch (SQLException ex) {
        throw new DDLException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new DDLException(ex.getMessage(), ex);
    }
}

From source file:org.easyrec.utils.spring.store.dao.DaoUtils.java

/**
* get a Blob object from a result set column with given name or null if no such
* column exists in the result set/*from   w  w w .  ja v  a2 s  .  c o  m*/
*
* @param rs         rs
* @param columnName columnName
* @return the value, which may be <code>null</code>
* @throws SQLException SQLException
*/
public static Blob getBlobIfPresent(ResultSet rs, String columnName) throws SQLException {
    int colIndex;
    try {
        colIndex = rs.findColumn(columnName);
    } catch (SQLException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "getBlob() failed for column '" + columnName + "'. ResultSet doesn't contain that column");
        }
        return null;
    }
    return rs.getBlob(colIndex);
}

From source file:com.xqdev.sql.MLSQL.java

private static void addResultSet(Element root, ResultSet rs) throws SQLException {
    Namespace sql = root.getNamespace();

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    while (rs.next()) {
        Element tuple = new Element("tuple", sql);
        for (int i = 1; i <= columnCount; i++) {
            String colName = rsmd.getColumnName(i); // names aren't guaranteed OK in xml
            String colTypeName = rsmd.getColumnTypeName(i);

            // Decode a BLOB if one is found and place it into the result as a encoded Base 64 string
            String colValue = "";
            if ("BLOB".equalsIgnoreCase(colTypeName)) {
                Blob b = rs.getBlob(i);
                if (b != null && b.length() > 0) {
                    Base64 b64 = new Base64();
                    String b64Blob = b64.encodeBase64String(b.getBytes(1, (int) b.length()));
                    colValue = b64Blob;
                } else
                    colValue = "";
            } else {
                colValue = rs.getString(i);
            }//w  w w.  j  a  v  a2  s  .com

            boolean wasNull = rs.wasNull();
            Element elt = new Element(colName);
            if (wasNull) {
                elt.setAttribute("null", "true");
            }
            if ("UNKNOWN".equalsIgnoreCase(colTypeName)) {
                tuple.addContent(elt.setText("UNKNOWN TYPE")); // XXX ugly
            } else {
                tuple.addContent(elt.setText(colValue));
            }
        }
        root.addContent(tuple);
    }

}