我正在尝试从 mysql 数据库中获取图像,图像存储为 blob。到目前为止,我已经尝试了三种或多或少不同的方式,但似乎没有一种方式能带我到任何地方。我一定是在这里犯了一些愚蠢的错误。
try {
// create a java mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(mySettings.dbConnect, mySettings.dbUser, mySettings.dbPass);
PreparedStatement stmt = conn.prepareStatement("select up.userid, up.name, la.languages, up.photo, up.dob, up.edited from userprofile up join languages la on up.languages_id = la.languages_id where up.userid = ?");
stmt.setString(1, userid);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// version 1
InputStream photois = rs.getBinaryStream("photo");
int ch;
String str = new String();
while ((ch = photois.read()) != -1) {
// here the exception occures when i InputStream.read().
// both Exception.getMessage() and Exception.getCause()
// of the caught exception yield null
str += (char)ch;
}
byte[] bdata=str.getBytes();
byte[] img64 = Base64.encode(bdata);
String photo64 = new String(img64);
// version 2
Blob b = rs.getBlob("photo");
byte[] ba = b.getBytes(1, b.length());
// b.length() throws exception, no message, no cause
byte[] img64 = Base64.encode(ba);
String photo64 = new String(img64);
// version 3
InputStream photois = rs.getBinaryStream("photo");
byte[] buf = IOUtils.toByteArray(photois);
// this throws an exception, message and cause both null as above
String photo64 = DatatypeConverter.printBase64Binary(buf);
}
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! (reading userprofile from db)");
System.err.println(e.getMessage());
System.err.println(e.getCause());
}
在所有情况下,控制台都会给我这个:
最佳答案
getMessage() 和 getCause() 中为 null 的异常是 NullPointerException。
ResultSet#getBinaryStream() 的 JavaDoc声明它为包含 SQL NULL 的列返回 null。尽管 ResultSet#getBlob() 的 JavaDoc省略相同的内容,在我看来,测试行不包含 blob 列中的任何数据,即 blob 在数据库中为 NULL。
关于java - 如何在 java 中将 java.sql.blob 转换为 base64 编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26402487/