您好我正在使用servlet从oracle数据库中读取BLOB图像并将其显示在html页面中
我的示例代码是
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String driver = "oracle.jdbc.driver.OracleDriver";
final String url = "jdbc:oracle:thin:@//157.227.32.153:1521/DNADB5";
final String username = "flex_user";
final String password = "flex_user";
int id=Integer.parseInt(request.getParameter("id"));
String query = "SELECT img_id,MP_ID , icon FROM Account_images where MP_ID=" +id;
ServletOutputStream out = response.getOutputStream();
try {
System.out.println("Getting connection");
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
response.setContentType("text/html");
if (rs.next()) {
InputStream in = rs.getBinaryStream("icon");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len=0;
while ((len=in.read(buffer)) != -1) {
// System.out.println("writing " + length + " bytes");
out.write(buffer, 0, len);
}
System.out.println("writed.");
in.close();
out.flush();
}
使用此代码,我可以显示单个图像,但我需要显示具有相同MP_ID的所有图像。 谁能帮助我?
提前致谢..
答案 0 :(得分:0)
尝试使用“while”而不是“if”。 (“if”不是循环。) 有点像...
try {
System.out.println("Getting connection");
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
response.setContentType("text/html");
/*if (rs.next()) { */ // INCORRECT
if(!rs.isBeforeFirst()){
/* NO DATA */
} else {
/* YOU HAVE DATA */
while(rs.next()){
InputStream in = rs.getBinaryStream("icon");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len=0;
while ((len=in.read(buffer)) != -1) {
// System.out.println("writing " + length + " bytes");
out.write(buffer, 0, len);
}
System.out.println("writed.");
in.close();
out.flush();
}
这将遍历结果集中的所有结果,而不仅仅是第一个结果。