I am using mysql
as my database. I am getting byte array in my java code. Then I am storing this byte array in Database as LONGBLOB
. Now while retrieving it back from db, I am using below code:
package com.sendSms;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
public class SampleTest {
public Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/forTest","root","123456");
}catch(Exception ex){}
return con;
}
public byte[] getFromDb(){
byte[] arr=null;
try{
Connection con = getConnection();
PreparedStatement pstmt=con.prepareStatement("select id,image from TestAndroid where id = ?");
pstmt.setInt(1, 16);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
// int id=rs.getInt("id");
arr = rs.getBytes("image");
}
}
catch(Exception ex){ex.printStackTrace();}
return arr;
}
public void go() throws IOException{
byte[] arr=getFromDb();
InputStream is=new ByteArrayInputStream(arr);
BufferedImage bi= ImageIO.read(is);
if(bi==null){
System.out.println("bi is NULL");
}
else{
System.out.println("bi is NOT NULL");
}
}
public static void main(String[] args) throws IOException {
SampleTest st = new SampleTest();
st.go();
}
}
When I am running this code I am getting BufferedImage
as null; although byte array is Not Null at this point. How can get this BufferedImage
. I need BufferedImage
because I need to pass it to other function, that accepts only BufferedImage. How can I resolve this issue.
Also when storing byte array in db, I am using:
setBytes(byte array)
method on PreparedStatement
& in Db I am using LONGBLOB
data type for storing this byte array.