Я пытаюсь получить изображение из базы данных mysql, где оно хранится как blob. до сих пор я пробовал три более или менее разных способа, без которых я, кажется, беру меня куда угодно. я должен совершить какую-то глупую ошибку.как преобразовать java.sql.blob в кодировку base64 в java
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());
}
во всех случаях консоль дает мне это:
Вы не сказали нам, что произошло в ваших попытках. Версия 3 выглядит как самая правдоподобная для меня - я сам не использовал «DatatypeConverter» и обычно рекомендую http://iharder.net/base64, но принцип в порядке. Скажите, пожалуйста, что вы наблюдаете. –
@JonSkeet: спасибо, что посмотрели. во всех трех версиях исключение выловлено и на консоли getMessage, а также getCause печатает нуль. –
Вы уверены, что есть действительно данные в блобе? Похоже, все вызовы rs.get * возвращают null. Согласно JDBC JavaDoc это происходит, когда столбец содержит SQL NULL. – Michal