10

What is the easiest way to convert byte array into Blob data type in MYSQL with java programming language?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
androidGuy
  • 5,553
  • 12
  • 39
  • 56
  • Have you tried anything yourself? Googling "java convert byte[] to sql.blob" gives a lot of hits .. – Wivani Jul 12 '11 at 10:39
  • well i have been googling for some time now,thats y i finally thought of posting it here.I did convert byte array to a serialblob bt had a problem converting it back to a bytearray since my table column was of type blob.I am here to get a proper way of converting a byte array into a blob,thanks:) – androidGuy Jul 12 '11 at 10:45

3 Answers3

8
Blob blob = connection.createBlob();
blob.setBytes(1, bytes);
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 2
    well, you need the connection object, obviously :) – Bozho Feb 21 '12 at 09:30
  • `setBytes()` returns number of bytes written. Should we write it inside loop for partial write? or single line of code will suffice? I have a 50KB `byte[]` all in memory which I want to save. – Majid Azimi Sep 16 '12 at 11:16
3

Blob fileBlob = new javax.sql.rowset.serial.SerialBlob(byteArray);

1

You may try this one, if you are using hibernate.. Possibly the easiest way! :)

Blob blob = Hibernate.createBlob(bytes);
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Sirish
  • 917
  • 3
  • 14
  • 25
  • 4
    this is deprecated. See http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Hibernate.html#createBlob(java.io.InputStream) – Adriano Oct 03 '12 at 12:59