Search code examples
javahtmlmysqldatabaseresultset

Printing SQL select result set directly onto HTML webpage?


How can I rewrite my code below to print the results directly on my webpage instead of on the console?

 public static void doSQL() {
        try {
            String url = "jdbc:msql://...";
            Connection conn = DriverManager.getConnection(url,"user","password");
            Statement stmt = conn.createStatement();
            ResultSet rs;

            rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
            while ( rs.next() ) {

                // I want to print the ResultSet directly on my HTML page, how may I go about doing that?
                String lastName = rs.getString("Lname");
                System.out.println(lastName);
            }
            conn.close();
        } catch (Exception e) {

            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }
    }
}

Solution

  • One method is to obtain a writer from the servlet response and then write the HTML content you want. I made a slight refactor of your doSQL() method to accept a PrintWriter as a parameter.

    public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        doSQL(pw);
    }
    
    public static void doSQL(PrintWriter pw) {
        try {
            String url = "jdbc:msql://...";
            Connection conn = DriverManager.getConnection(url,"user","password");
            Statement stmt = conn.createStatement();
            ResultSet rs;
    
            rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
            pw.println("<html><table>");
            while (rs.next()) {
                // you only select one field, but you can easily adapt
                // this code to have more fields (i.e. table columns)
                String lastName = rs.getString("Lname");
                pw.println("<tr><td>" + lastname + "</td></tr>");
            }
            pw.println("</table></html>");
            conn.close();
        } catch (Exception e) {
    
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }
    }