Example usage for java.sql Blob getBytes

List of usage examples for java.sql Blob getBytes

Introduction

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

Prototype

byte[] getBytes(long pos, int length) throws SQLException;

Source Link

Document

Retrieves all or part of the BLOB value that this Blob object represents, as an array of bytes.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);//from   ww w . j a va2s . c om

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT col_blob FROM mysql_all_table");

    if (rs.next()) {
        Blob blob = rs.getBlob("col_blob");
        long blobLength = blob.length();

        int pos = 1; // position is 1-based
        int len = 10;
        byte[] bytes = blob.getBytes(pos, len);

        InputStream is = blob.getBinaryStream();
        int b = is.read();
    }
}

From source file:Blobs.java

public static void main(String args[]) {
    if (args.length != 1) {
        System.err.println("Syntax: <java Blobs [driver] [url] " + "[uid] [pass] [file]");
        return;//from www .ja  v a2 s .  co  m
    }
    try {
        Class.forName(args[0]).newInstance();
        Connection con = DriverManager.getConnection(args[1], args[2], args[3]);
        File f = new File(args[4]);
        PreparedStatement stmt;

        if (!f.exists()) {
            // if the file does not exist
            // retrieve it from the database and write it to the named file
            ResultSet rs;

            stmt = con.prepareStatement("SELECT blobData " + "FROM BlobTest " + "WHERE fileName = ?");

            stmt.setString(1, args[0]);
            rs = stmt.executeQuery();
            if (!rs.next()) {
                System.out.println("No such file stored.");
            } else {
                Blob b = rs.getBlob(1);
                BufferedOutputStream os;

                os = new BufferedOutputStream(new FileOutputStream(f));
                os.write(b.getBytes(0, (int) b.length()), 0, (int) b.length());
                os.flush();
                os.close();
            }
        } else {
            // otherwise read it and save it to the database
            FileInputStream fis = new FileInputStream(f);
            byte[] tmp = new byte[1024];
            byte[] data = null;
            int sz, len = 0;

            while ((sz = fis.read(tmp)) != -1) {
                if (data == null) {
                    len = sz;
                    data = tmp;
                } else {
                    byte[] narr;
                    int nlen;

                    nlen = len + sz;
                    narr = new byte[nlen];
                    System.arraycopy(data, 0, narr, 0, len);
                    System.arraycopy(tmp, 0, narr, len, sz);
                    data = narr;
                    len = nlen;
                }
            }
            if (len != data.length) {
                byte[] narr = new byte[len];

                System.arraycopy(data, 0, narr, 0, len);
                data = narr;
            }
            stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, " + "blobData) VALUES(?, ?)");
            stmt.setString(1, args[0]);
            stmt.setObject(2, data);
            stmt.executeUpdate();
            f.delete();
        }
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static byte[] getBLOB(int id, Connection conn) throws Exception {
    ResultSet rs = null;/*from   w  ww .  j a  v  a2 s .c  o m*/
    PreparedStatement pstmt = null;
    String query = "SELECT photo FROM MyPictures WHERE id = ?";
    try {
        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:Main.java

public static byte[] getBLOB(int id, Connection conn) throws Exception {
    ResultSet rs = null;/*w w w  .  j  a  va  2s .  c o  m*/
    PreparedStatement pstmt = null;
    String query = "SELECT photo FROM MyPictures WHERE id = ?";
    try {
        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:procuradoria.pdf.util.DocumentsPdf.java

public static void byteArrayToFile(Uzatdocs doc) {
    try {/*from w  ww.  jav a2s  .c om*/
        Blob blob = doc.getUzatdocsArchivo();

        int blobLength = (int) blob.length();
        byte[] bArray = blob.getBytes(1, blobLength);
        blob.free();
        OutputStream out = new FileOutputStream("out.pdf");
        out.write(bArray);
        out.close();
    } catch (Exception ex) {
        log.level.info(">> Exception " + ex.getMessage());
    }
}

From source file:procuradoria.pdf.util.DocumentsPdf.java

public static Boolean CreateFilePDF(Uzatdocs document, String filePath) {
    Boolean exito = false;//w ww. jav a  2 s. c om
    try {
        String fileName = document.getId().getUzatdocsId() + ".pdf";
        Blob blob = document.getUzatdocsArchivo();
        int blobLength = (int) blob.length();
        byte[] bArray = blob.getBytes(1, blobLength);
        OutputStream out = new FileOutputStream(filePath + fileName);
        out.write(bArray);
        out.close();
        exito = true;
    } catch (Exception ex) {
        log.level.info(">> Exception " + ex.getMessage());
    }
    return exito;
}

From source file:io.confluent.connect.jdbc.EmbeddedDerby.java

private static String formatLiteral(Object value) throws SQLException {
    if (value == null) {
        return "NULL";
    } else if (value instanceof CharSequence) {
        return "'" + value + "'";
    } else if (value instanceof Blob) {
        Blob blob = ((Blob) value);
        byte[] blobData = blob.getBytes(1, (int) blob.length());
        return "CAST(X'" + DatatypeConverter.printHexBinary(blobData) + "' AS BLOB)";
    } else if (value instanceof byte[]) {
        return "X'" + DatatypeConverter.printHexBinary((byte[]) value) + "'";
    } else {//from   w  w  w .  j av  a 2 s  . c  om
        return value.toString();
    }
}

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

private static byte[] getBlobValue(Blob blob) throws SQLException {
    if (blob == null) {
        return null;
    }/*w  ww.j a  va2s . c  o  m*/

    if (blob.length() > Integer.MAX_VALUE) {
        log.warn("Blob truncated: value larger then Integer.MAX_VALUE bytes:" + blob.length());
        return null;
    }
    int len = (int) blob.length();
    return blob.getBytes(1, len);
}

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  w w . j  a va  2  s  . 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:br.com.itfox.utils.Utils.java

public static String blobToString(Blob blob) {
    try {//from w ww  .  j  ava 2  s. c  o  m
        if (blob != null) {
            byte[] bdata = blob.getBytes(1, (int) blob.length());
            String text = new String(bdata);
            text = text.replaceAll("\r\n", "<br>");
            return text;
        }
    } catch (SQLException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}