[英]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 下面的代码用于将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();
The code below is the one for extracting the BLOB and converting it back to 2d array 下面的代码是用于提取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();
}
}
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
: 您正在手动将float
写入DataOutputStream
您可以使用ObjectOutputStream
将整个float[]
序列化为byte[]
:
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: 要阅读,只需使用ObjectInputStream
装饰Blob
二进制流:
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. 记住要在第二种情况下关闭流-我已经使用Java 7 try-with-resources来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.