如何使用JAVA从mySQL数据库中提取BLOB(从2d数组到BLOB)

时间:2014-02-08 09:31:18

标签: java mysql

以下代码用于将2darray转换并插入BLOB到数据库中

    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();

下面的代码是用于提取BLOB并将其转换回2d数组的代码

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();
        }
    }

但是这段代码从二维数组中给出了错误的数字。

1 个答案:

答案 0 :(得分:1)

您是手动将float写入DataOutputStream - 您可以使用float[]将整个byte[]序列化为ObjectOutputStream

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

要阅读,只需使用ObjectInputStream来装饰Blob二进制流:

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

请记住在第二种情况下关闭流 - 我使用了Java 7 try-with-resources来执行此操作。