How to manipulate a BLOB in Java?
I have a DB procedure which returns a BLOB. Can anyone tell me how to m开发者_StackOverflow中文版anipulate the BLOB? Is there any specific API for this?
Is there any specific API for this ?
Sure, the JDBC API.
- Trail: JDBC™ Database Access
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:
Work with a byte-array:
- Get hold of a
byte[]
containing the data throughBlob.getBytes
- Manipulate this byte-array
- Set it back using
Blob.setBytes
.
- Get hold of a
Work with
InputStream
/OutputStream
:- Get hold a an
InputStream
throughBlob.getBinaryStream
- Manipulate this stream as you see fit
- Use
Blob.setBinaryStream
.
- Get hold a an
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.
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;
}
}
With Simple Java JDBC Api, you can get a java.sql.Blob
back from a ResultSet
.
ResultSet.getBlob(index)
orResultSet.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()
.
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
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();
}
}
精彩评论