2
我想從mysql數據庫中獲取圖像,並將其存儲爲blob。到目前爲止,我已經嘗試了三種或多或少的不同方式,其中不包括任何其他方式。我必須在這裏犯一些愚蠢的錯誤。如何將java.sql.blob轉換爲java中的base64編碼字符串
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,但原理很好。請告訴我們你正在觀察的內容。 – 2014-10-16 10:52:17
@JonSkeet:謝謝你的採訪。在所有三個版本中都會捕獲異常,並在控制檯上獲取getMessage以及getCause print null。 – 2014-10-16 11:58:08
你確定blob中有真正的數據嗎?看起來像所有的rs.get *調用都返回null。根據JDBC JavaDoc,當列包含SQL NULL時會發生這種情況。 – Michal 2014-10-16 12:14:07