Easiest way to convert a Blob into a byte array
Asked Answered
F

3

55

what is the easiest way to convert a Blob into a byte array?I am using MYSQL and i want to convert a Blob datatype into a byte array.

Iam using java programming language:)

Francophile answered 12/7, 2011 at 10:1 Comment(0)
O
90

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();
Ogham answered 12/7, 2011 at 10:12 Comment(6)
Thanks,actually blob is not having getbytes() method,only serialblob is having getbytes() method.How to do it for blob.Francophile
are you using java.sql.Blob?Ogham
this method gives a Lob is closed exception... what do I do ?Scribbler
@AnuShibinJosephRaj i think you should post a full question on SO with an example of your code attached.Ogham
is it a good way to just convert a blob in binary and send via httpclient post request?Yakka
@Yakka that depends entirely on your situation. what i can tell you in advance is that it won't be very fast..Ogham
C
60

The easiest way is this.

byte[] bytes = resultSet.getBytes("my_field");
Cisterna answered 12/7, 2011 at 10:42 Comment(4)
Excuse me, but I really I have not understood what rs is.Beefburger
@MarcoSulla: A JDBC ResultSetCisterna
I believe this answer is valid only when the field is less than 1048576 bytes.Illustrational
@AJ.P: This depends on the SQL dialect. In many dialects, there is no such restriction.Cisterna
E
0

You can also get bytes array from Blob instance by this way:

Blob myBlob = null;
byte[] bytes = myBlob.getBinaryStream().readAllBytes();
Enrobe answered 20/10, 2022 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.