如何在java中将java.sql.blob转换为base64编码字符串
我试图从mysql数据库中获取一个图像,该数据库将图像存储为blob。到目前为止,我已经尝试了三种或多或少不同的方法,其中没有一种似乎能把我带到任何地方。我一定是犯了什么愚蠢的错误如何在java中将java.sql.blob转换为base64编码字符串,java,mysql,base64,blob,Java,Mysql,Base64,Blob,我试图从mysql数据库中获取一个图像,该数据库将图像存储为blob。到目前为止,我已经尝试了三种或多或少不同的方法,其中没有一种似乎能把我带到任何地方。我一定是犯了什么愚蠢的错误 try { // create a java mysql database connection String myDriver = "org.gjt.mm.mysql.Driver"; Class.forName(myDriver);
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
JavaDoc for声明它为包含SQL null的列返回null。尽管JavaDoc for the没有提到这一点,但在我看来,测试行在blob列中不包含任何数据,即blob在数据库中为NULL。您还没有告诉我们在任何尝试中发生了什么。对我来说,第3版似乎是最合理的版本——我自己没有使用过“DatatypeConverter”,通常我会推荐它,但其原理很好。请告诉我们你在观察什么。@JonSkeet:谢谢你的观察。在所有三个版本中都会捕获异常,并且控制台上会显示getMessage和getCause print null。您确定blob中确实有数据吗?看起来所有rs.get*调用都返回null。根据JDBC JavaDoc,当列包含SQL NULL时会发生这种情况。@Michal:我现在觉得自己很愚蠢。你是对的。我用于测试的特定数据行在blob中为null。非常感谢。如果你想获得荣誉,请随意添加一个我可以接受的答案。