简体   繁体   中英

How to pull BLOB(from 2d array to BLOB) from mySQL database using JAVA

The code below is for converting and inserting 2darrays into BLOB into the database

    ByteArrayOutputStream bas = new ByteArrayOutputStream();
    DataOutputStream ds = new DataOutputStream(bas);
    for (float f : secondArray) 
        ds.writeFloat(f);
    byte[] bytes = bas.toByteArray();
    java.sql.Blob b1 = new SerialBlob(bytes);

    PreparedStatement state = conn.prepareStatement("INSERT INTO blob_table (id, for_blob) " + " VALUES(6,?)");
    state.setBlob(1, b1);
    state.executeUpdate();

The code below is the one for extracting the BLOB and converting it back to 2d array

Statement state1 =  conn.createStatement();
    ResultSet rs = state1.executeQuery("SELECT * FROM blob_table WHERE id = 6");

    while(rs.next()){
        try{
            Blob blob1 = rs.getBlob(1);
            byte[] bytesInBlob = blob1.getBytes(1, (int) blob1.length());

            ByteArrayInputStream bas1 = new ByteArrayInputStream(bytesInBlob);
            DataInputStream dis = new DataInputStream(bas1);
            float[] fArr = new float[bytesInBlob.length / 4];  // 4 bytes per float
            for (int i = 0; i < fArr.length; i++)
            {
                fArr[i] = dis.readFloat();
            }
            for(int i=0;i<fArr.length;i++)
                System.out.println(fArr[i]);            

        }catch(Exception i){
            i.printStackTrace();
        }
    }

But this code gives me the wrong numbers from the 2d array.

You are manually writing float s to a DataOutputStream - you can serialize the whole float[] to a byte[] using an ObjectOutputStream :

final ByteArrayOutputStream baos = new ByteArrayOutputStream();        
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(data);
ps.setBlob(1, new SerialBlob(baos.toByteArray()));

To read you simply use a ObjectInputStream to decorate the Blob binary stream:

try (final ObjectInputStream ois = new ObjectInputStream(rs.getBlob(1).getBinaryStream())) {
    data = (float[]) ois.readObject();
}

Remember to close the stream in the second case - I have used a Java 7 try-with-resources to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM