如何将sql查询的结果发布到servlet中?

时间:2011-04-11 00:33:57

标签: java sql servlets

我一直坚持这个。

这是我的servlet:

package HWpackage;

import java.io.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoData extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Demo of Data Persistence</title>");
            out.println("</head>");
            out.println("<body>");

        try {
              String driver = "oracle.jdbc.driver.OracleDriver";
              String url = "jdbc:oracle:thin:@coit-ora01.uncc.edu:1521:class";
              String username = "johnR";
              String password = "lAylko0K";

              // Load database driver if it's not already loaded.
              Class.forName(driver);
              // Establish network connection to database.
              Connection connection =
                DriverManager.getConnection(url, username, password);
              // Create a statement for executing queries.
              Statement statement = connection.createStatement();
              String query =
                "SELECT sum(cost) FROM stocks where username = 'Bora'";
              // Send query to database and store results.
              ResultSet resultSet = statement.executeQuery(query);

              while(resultSet.next()) {


                out.println("Your total cost is" );


              }
              connection.close();
            } catch(ClassNotFoundException cnfe) {
              System.err.println("Error loading driver: " + cnfe);
              // Useful when you debug your program on the coit server
              // where System.out.println("") becomes futile
              out.println("<tr>  Error loading driver: " + cnfe);
              out.println("</tr>");
            } catch(SQLException sqle) {
              System.err.println("Error with connection: " + sqle);
              // Again, for debug purpose
              out.println("<tr>  Error with connection: " + sqle);
              out.println("</tr>");
            }

            out.println("</table>");
            out.println("</body>");
            out.println("</html>");
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */

    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

我想知道在servlet中发布此查询结果的正确方法:

String query =
                "SELECT sum(cost) FROM stocks where username = 'Bora'";

之后

out.println("Your total cost is" );

如果有人能提供给我这些信息,那么你将会认真对待我。谢谢大家。

2 个答案:

答案 0 :(得分:3)

其中一种方法是: -

  1. SELECT sum(cost) AS COST FROM stocks where username = 'Bora'

  2. 在此代码块中修改为:

  3.   

    while(resultSet.next()){

                Double cost = resultSet.getDouble("COST");   
                out.println("Your total cost is" + cost ); 
    
         

    }

    旁注:

    1. 不要用这种方式硬编码sql参数。您很容易发生SQL injection次攻击。使用参数标记即。 `SELECT sum(cost) AS COST FROM stocks where username = ?和JDBC PreparedStatement来执行它。
    2. 创建一个单独的DAO类来处理所有数据库工作。这将促进代码中的分离。

答案 1 :(得分:0)

out.println("Your total cost is "+resultSet.getString("sum(cost)"));