Development Island

Using JDBC with JSP

This page gives brief details how to access your database via a jsp using JDBC.
Note that connection details do not need to be supplied as your datasource as been preconfigured. Datasources are available by using the JNDI name of "java:comp/env/jdbc/db_username" where username should be replaced with your account name. Please note that Postgres users should use the JNDI name of "java:comp/env/jdbc/pgdb_username" instead.

Next is example jsp code showing the connecting to a database and submition of a simple query.

<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>