Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a java.sql.Blob object in Java SE 1.5.0 with a byte[] input?

Tags:

java

jdbc

blob

I want to create a Blob object from a byte[] input to update a table using PreparedStatement#setBlob(). In J2SE 6, we have java.sql.Connection#createBlob() to get this done. Is there anything similar to this available in J2SE 1.5.0? What is the best way to update a BLOB type column with a byte[] data in J2SE 1.5.0?

like image 219
ssethupathi Avatar asked Jun 08 '11 12:06

ssethupathi


People also ask

How do you create a BLOB byte array?

Convert Byte Array to BLOB in Java with an Easy Example Then created a BLOB object initialized with null. Next, I have Converted the file into a Byte array ( byte[] ), stored it into my_byte_array. Finally converted the byte array into BLOB using SerialBlob() method.

How do you represent a BLOB in Java?

To represent a BLOB data type, we use K, M, and G characters that represent the multiples of 1024, 1024*1024, 1024*1024*1024, respectively. The lifespan of a BLOB ends when a transaction commits. We should use the BLOB data type if we want to store very large binary values.

What is Blob object in Java?

A Blob object represents the Java programming language mapping of an SQL BLOB (Binary Large Object). An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table.


2 Answers

An example, using SerialBlob:

import java.sql.Blob;
import javax.sql.rowset.serial.SerialBlob;

byte[] byteArray = .....;
Blob blob = new SerialBlob(byteArray);
like image 171
Buhake Sindi Avatar answered Oct 23 '22 03:10

Buhake Sindi


You don't have to worry about creating Blob objects at all. Treat them as blobs on the database, and byte[]s in Java. For example:

@Entity
@Table(name = "some.table")
public class MyEntity
{
    @Id
    int myId;

    @Lob
    byte[] myBlob;

    // snip getters & setters
}

If you're really intent on creating a Blob instance yourself, you can use the SerialBlob implementation:

byte[] bytes = ...;
Blob myBlob = new SerialBlob(bytes);
like image 25
Matt Ball Avatar answered Oct 23 '22 03:10

Matt Ball