如何格式化从数据库中检索的数据

时间:2017-11-17 11:01:06

标签: java html

请帮我格式化从数据库中检索的数据。我想从数据库中检索数据并将其显示在网页中。 这里使用的数据库是postgres。 netbeans平台用于开发Web应用程序。

我将输出作为单行

eg-SSN :1 Subbu TVM SSN :2 Kailas KZH

我希望它在不同的行中

eg-
SSN :1 Subbu TVM 
SSN :2 Kailas KZH

我的代码:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class view extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
 out.println("<html>");
    out.println("<head><title>All Employees</title></head>");
    out.println("<body>");
    out.println("<center><h1>All Employees</h1>");
    String ls=System.getProperty("line.separator");
    Connection con = null;
    Statement stmt = null;
    try {
      Class.forName("org.postgresql.Driver");
      con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Project","postgres","1234");
      stmt = con.createStatement();


      ResultSet rs = stmt.executeQuery("SELECT * FROM chef;");
      while (rs.next()) {
        String ssn = rs.getString("ssn");
        String cname = rs.getString("cname");
        String allocation = rs.getString("allocation");
        out.println("SSN :"+ssn+"  "+cname+"  "+allocation);

        //out.print("ssn : " + ssn +"\n" );
        //out.print("name : "+cname+"\n" );
        //out.print("allocation : "+allocation+"\n" );

      }
      rs.close();

    } catch (SQLException e) {
      out.println("An error occured while retrieving " + "all employees: " 
          + e.toString());
    } catch (ClassNotFoundException e) {
      throw (new ServletException(e.toString()));
    } finally {
      try {
        if (stmt != null) {
          stmt.close();
        }
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
      }
    }
   out.println("</center>");
    out.println("</body>");
    out.println("</html>");
    out.close();
  }
}

1 个答案:

答案 0 :(得分:1)

  

只需使用<br/>

即可

out.write("<br />");
out.write("SSN :"+ssn+" "+cname+" "+allocation);