1

嗨,我正在使用 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 的所有图像。谁能帮帮我??

提前致谢..

4

1 回答 1

0

尝试使用“while”而不是“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();
         }

这将遍历结果集中的所有结果,而不仅仅是第一个。

于 2013-03-26T05:50:04.383 回答