[英]how to convert a java.sql.blob to a base64 encoded string in java
我試圖從存儲為blob的mysql數據庫中獲取圖像。 到目前為止,我嘗試了三種或多或少的不同方法,但似乎沒有一種方法可以帶我到任何地方。 我一定在這里犯了一些愚蠢的錯誤。
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.