BD.java 2.66 KB
Newer Older
1 2
package com.roshka.bootcamp;

3 4
import jakarta.servlet.ServletConfig;
import jakarta.servlet.annotation.WebInitParam;
5 6 7 8 9 10 11 12
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.PrintWriter;
import java.sql.*;

13 14 15 16 17
@WebServlet(urlPatterns = "/conexion", initParams = {@WebInitParam(name = "dbUrl", value = "jdbc:postgresql://localhost:5432/bootcamp_market"),
        @WebInitParam(name = "dbUser", value = "postgres"),
        @WebInitParam(name = "dbPassword", value = "postgres"),
})

18 19
public class BD extends HttpServlet {
    Connection connection;
20 21

    public void init(ServletConfig config) {
22 23 24
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager
25
                    .getConnection(config.getInitParameter("dbUrl"), config.getInitParameter("dbUser"), config.getInitParameter("dbPassword"));
26 27
        } catch (Exception e) {
            e.printStackTrace();
28
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
            System.exit(0);
        }
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        try {
            Statement stmt = connection.createStatement();
            res.setContentType("text/html");
            PrintWriter out = res.getWriter();
            ResultSet rs = stmt
                    .executeQuery("select a.nombre, apellido, count(b.cliente_id) Cantidad_factura from cliente a " +
                            "inner join factura b " +
                            "on a.id=b.cliente_id " +
                            "group by a.nombre, a.apellido " +
                            "order by Cantidad_factura desc;");
            out.println("<html>");
            out.println("<body>");
            while (rs.next()) {
                String nombre = rs.getString("nombre");
                String apellido = rs.getString("apellido");
                int cantidad = rs.getInt("Cantidad_factura");

52 53 54
                out.println("<p>NOMBRE = " + nombre + "</p>");
                out.println("<p>APELLIDO = " + apellido + "</p>");
                out.println("<p>CANTIDAD FACTURA = " + cantidad + "</p>");
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

            }
            out.println("</body>");
            out.println("</html>");
            rs.close();
            stmt.close();
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }

    }


    public void destroy() {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}