简体   繁体   中英

How to post the result of a sql query into a servlet?

I keep getting stuck on this.

Here is my 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>

}

I'd like to know the correct way to post the result of this query in the servlet:

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

after the is

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

If someone could provide me that information you will seriously make my night. Thanks everyone.

One of the ways is to do this:-

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

  2. In this code block modify to:

while(resultSet.next()) {

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

}

Side notes:

  1. Do not hard code sql parameters this way. You are prone to SQL injection attacks. Use parameter markers ie. `SELECT sum(cost) AS COST FROM stocks where username = ? and JDBC PreparedStatement to execute it.
  2. Create a separate DAO class for handing all database work. This will promote decoupling in your code.
out.println("Your total cost is "+resultSet.getString("sum(cost)"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM