2

I want to create SQL query that returns some values and one of those values is blob.

When I just put blob column in my select it returns BigDecimal :|

its plain JDBC query with parameters

3 Answers 3

3

Take a look at the javadocs section on Materializing Blob Data.

You need to call getBlob on the blob column and then read the binary stream.

    Blob blob = rs.getBlob("BLOB_COLUMN_NAME");        
    InputStream blobStream = blob.getBinaryStream();

    //e.g. save blob to a file
    FileOutputStream out = new FileOutputStream("file.txt");
    byte[] buffer = new byte[1024];
    int n = 0;  
    while( (n = blobStream.read(buffer)) != -1 ) {
        out.write(buffer, 0, n);
    }
    out.flush();
    out.close();
    blobStream.close();
Sign up to request clarification or add additional context in comments.

Comments

1

Inserting..

stmt = con.prepareStatement("INSERT INTO TABLE(fileName, "
            + "blobData) VALUES(?, ?)");
        stmt.setString(1, "somefilename");
        stmt.setObject(2, data);//data is byte[]
        stmt.executeUpdate();

Selecting..

ResultSet rs;

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

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

1 Comment

actually setBytes() (instead of setObject()) might be more portable. But that depends heavily on the JDBC driver
1

Try to call the method getBytes() from the ResultSet:

stmt = dbConn.prepareStatement("SELECT ...");
ResultSet rs = stmt.executeQuery();
byte[] blob = rs.getBytes(1);

This should return your blob object as a byte array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.