How to retrieve sql table with all its data using java

Predator Ajmera picture Predator Ajmera · Jan 10, 2013 · Viewed 8.7k times · Source

I am trying to make a Java EE project with SQL as my database and glassfish as my server. I want to retrieve all the data in my table in to a html page but I have to use servlet and session beans. My output will be shown in a html page.

Answer

ronpy picture ronpy · Jan 10, 2013

An example

<%@ page language="java"%>
<%@ page import = "java.sql.Connection"%>
<%@ page import = "java.sql.DriverManager"%> 
<%@ page import = "java.sql.ResultSet"%> 
<%@ page import = "java.sql.Statement"%> 
<html>
<body>
<h1>Retrieve data</h1>
<%
try
{
   Class.forName("org.gjt.mm.mysql.Driver");
   Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/db", "user", "pass");
   if (!conexion.isClosed())
   {
      Statement st = conexion.createStatement();
      ResultSet rs = st.executeQuery("select * from contact");

      out.println("<table border=\"1\"><tr><td>Id</td>< td>Name</td><td>LastName</td><td>Phone</td></tr>");
      while (rs.next())
      {
         out.println("<tr>");
         out.println("<td>"+rs.getObject("id")+"</td>");
         out.println("<td>"+rs.getObject("Name")+"</td>");
         out.println("<td>"+rs.getObject("LastName")+"</td>");
         out.println("<td>"+rs.getObject("Phone")+"</td>");
         out.println("</tr>");
      }
      out.println("</table>");

      conexion.close();
   }
   else
      out.println("fail");
}
catch (Exception e)
{
   out.println("Exception " + e);
   e.printStackTrace();
}
%>
</body>
</html>