Friday, 11 January 2013

Using JDBC within a JSP

The code below is taken from http://www.devisland.net/help/jdbc_jsp.shtml with thanks

<HTML>

       <HEAD>
               <TITLE>DB Test</TITLE>
       </HEAD>

       <BODY>
               <%@ page language="java" import="java.sql.*,javax.naming.*,javax.sql.*" %>
               <%
              DataSource ds = null;
              Connection c = null;
              Statement Stmt = null;
              ResultSet RS = null;                                                                                    
              try{
                  Context initCtx = new InitialContext();
                  ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/db_user");
                  c = ds.getConnection();
                  out.println("querying database...<br>");
                  Stmt = c.createStatement();
                  RS = Stmt.executeQuery("SHOW tables");
                  while (RS.next()) {
                      out.println(RS.getString(1)+"<br>");
                  }
              }
              catch(Exception e){
                  out.println("ERROR! "+e.getMessage());
              }
              finally{
                  try{
                      if(RS != null){
                          RS.close();
                      }
                      if(Stmt != null){
                          Stmt.close();
                      }
                      if(c != null){
                          c.close();
                      }
                  }
                  catch(Exception e2){
                      out.println("Unable to close connection: "+e2.getMessage());
                  }
               }
               %>
       </BODY>
</HTML>


---

No comments:

Post a Comment