gpt4 book ai didi

java - 使用 Java 从 MySQL 读取一个 blob

转载 作者:行者123 更新时间:2023-11-29 04:48:38 24 4
gpt4 key购买 nike

我在使用 Java 从 MySQL 数据库读取 blob 时遇到问题。我需要用 jax-rs 编写一个 web 服务来传送保存在数据库中的图像。对于传输,它必须使用 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;
}

不知何故,它只返回这样的东西(解码后的结果列表):

java.io.ByteArrayInputStream@cc90a0a

最佳答案

问题在于“toString()”调用:binaryStream.toString(); BinaryInputStream 没有实现toString()。使用类似这样的方式读取字节:

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 - 使用 Java 从 MySQL 读取一个 blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com