用Java从MySQL读取blob [英] Reading a blob from MySQL with Java
本文介绍了用Java从MySQL读取blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用Java从MySQL数据库中读取blob时遇到问题。
我需要用jax-rs编写一个web服务来提供保存在数据库中的图像。对于传输,必须使用Base64进行编码。
I have a problem reading a blob from a MySQL database with Java. I need to write a webservice with jax-rs to deliver an image saved in the database. For transport, it has to be encoded using Base64.
这是我的代码:
public String getImage(@PathParam("id") int id) throws SQLException{
System.out.println(id);
String img64str = "null";
Blob image = null;
Connection conn = MySQLConnection.getInstance();
if(conn != null)
{
try{
// Anfrage-Statement erzeugen.
Statement query;
query = conn.createStatement();
// Ergebnistabelle erzeugen und abholen.
String sql = "SELECT bild FROM beitraege where id="+id;
ResultSet result = query.executeQuery(sql);
//Ergebniss zur�ckliefern
while (result.next()) {
System.out.println("while");
image = result.getBlob("bild");
InputStream binaryStream = image.getBinaryStream(1, image.length());
String str= binaryStream.toString();
byte[] bdata=str.getBytes();
byte[] img64 = Base64.encode(bdata);
img64str = new String(img64);
}
}catch (SQLException e) {
e.printStackTrace();
}
}
return img64str;
}
不知何故,它只返回这样的东西(显示结果列表已解码):
Somehow, it only returns something like this (shown result list decoded):
java.io.ByteArrayInputStream@cc90a0a
推荐答案
问题在于toString()调用: binaryStream.toString();
BinaryInputStream不实现 toString()
。
使用类似的东西来读取字节:
The problem lies in the "toString()" call: binaryStream.toString();
BinaryInputStream do not implement toString()
.
Use something like this to read the bytes:
int ch;
//read bytes from ByteArrayInputStream using read method
while((ch = binaryStream.read()) != -1)
{
System.out.print((char)ch);
// store it to an array...
}
这篇关于用Java从MySQL读取blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文