How to manipulate a BLOB in Java?
Asked Answered
L

5

11

I have a DB procedure which returns a BLOB. Can anyone tell me how to manipulate the BLOB? Is there any specific API for this?

Leticialetisha answered 17/10, 2011 at 7:9 Comment(1)
Such as the API for java.sql.Blob?Apprentice
H
16

Is there any specific API for this ?

Sure, the JDBC API.


You get hold of the Blob instance just as you get hold of any value from a result set. You should then use the get...- and set... methods on this Blob.

Here you basically have two options:

An alternative approach is to skip messing with Blob in the first place, and instead use the second approach (with streams) directly through the ResultSet-interface.

Harebrained answered 17/10, 2011 at 7:12 Comment(3)
My experience is that ResultSet.getBinaryStream() is more robust than working with instances of BlobParietal
@Harebrained : Thanks for the responses. But can anyone tell me how 'ResultSet.getBinaryStream()' is robust compared to 'Blob.getBinaryStream' ?Leticialetisha
If your driver supports ResultSet.getBlob and Blob.getBinaryStream, and you're fairly confident that you won't switch to another database, just go with the one you find most readable.Harebrained
C
5

It depends on which kind of blob contains (image, video) and it's extension. I wrote a simple program to retrieve an image from DB and show it in JSP page. Hope it helps.

JSP Page

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>                            
    <image src="blobAction"/> 
</body>

Servlet Page

byte[] imgData = blobDao.getInstance().getPhoto();
        response.setContentType("image/gif");
        OutputStream o = response.getOutputStream();
        o.write(imgData);
        o.flush();
        o.close();

Calling Procedure

public byte[] getPhoto() {

    byte[] imgData = null;
    Blob img = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {

        conn = getConnection();
        String sqlQ = "SELECT CONTENT_FILE FROM CONTENT where id = 'something';
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sqlQ);

        while (rs.next()) {
            img = rs.getBlob("CONTENT_FILE");
            imgData = img.getBytes(1, (int) img.length());
        }
        rs.close();
        stmt.close();
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {           
        return imgData;
    }
}
Conventicle answered 22/12, 2011 at 13:39 Comment(0)
P
3

With Simple Java JDBC Api, you can get a java.sql.Blob back from a ResultSet.

  1. ResultSet.getBlob(index) or
  2. ResultSet.getBlob(String columnName).

Both returns a Blob.

Once you get a Blob, you can get the byte[] back from the Blob.getBytes() method or set using setBytes() method.

Update: Seeing that some Database driver vendors don't support Blob, you can use ResultSet.getBinaryStream().

Philanthropy answered 17/10, 2011 at 7:14 Comment(3)
Why pointless? The existence of a BLOB datatype in the database has nothing to do with the support by the driver. Not all drivers support ResultSet.getBlob() some only support ResultSet.getInputStream()Parietal
@All : Thanks guys for the responses. If getBlob() is not supported by all then which method is good to use ? Blob.getBinaryStream() ?Leticialetisha
I usually do ResultSet.getBytes() and work with byte[] instead.Philanthropy
E
0

You can use javax.sql.rowset.serial.SerialBlob.

I'm using it in my SpringBoot & Angular4 application like this:

  • get Base64String from Angular4 app
  • decode Base64String to byte[]
  • create SerialBlob like this: SerialBlob serialBlob = new SerialBlob(byte[])
  • store it in the database with JpaRepository
Electrokinetics answered 9/1, 2018 at 15:48 Comment(0)
M
0

Example

public void Insert(Object obj){
        try {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(byteArray);
            oos.writeObject(obj);
            PreparedStatement ps= conn1.prepareStatement("insert into vehiculos values(?)");    
            ps.setBytes(1, byteArray.toByteArray());  
            ps.execute();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("ERROR:al hacer un Insert");   
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void ShowData(){
        try {
            Statement stmt = conn1.createStatement();
            String query = "SELECT * FROM vehiculos";
            ResultSet rs = stmt.executeQuery(query);
            Object obj;
            while(rs.next()){
                //Coche c = (Coche)rs.getBlob("coches");
                Blob blob = rs.getBlob("coches");
                ObjectInputStream ois = new ObjectInputStream(blob.getBinaryStream());
                obj = ois.readObject();
                System.out.println(obj.toString());
                System.out.println("");
                /*Blob blob = rs.getBlob("coches");
                byte[] data = blob.getBytes(1, (int)blob.length());*/
                
            }
            rs.close();
            stmt.close();
        
      } catch (SQLException ex) {
            System.out.println("ERROR:al consultar");
            ex.printStackTrace();
      } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void cerrar_Conexion (){
       
        try {  
        conn1.close();
      } catch (SQLException ex) {
            System.out.println("ERROR:al cerrar la conexión");
            ex.printStackTrace();
      }
    }
Margerymarget answered 7/2, 2022 at 0:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.