Søren Lund (slu) wrote,
Søren Lund
slu

HSQLDB Part 3 - Java Server Pages

Now in the previous installment of my notes regarding HSQLDB, I presented a very simple console program. It would connect to the database and lists the contents of the Bookmarks-table to the console.

Below is a webified version of the program. It's implemented as a single JSP file, TestDemobase.jsp. Store it in your webapps directory ($CATALINA_HOME/webapps/app/).

Note: this is absolutely not the way to do it. The code below is ugly and difficult to maintain. It is meant as a very simple example of connecting to a database from JSP.

<%@ page language="java" 
           import="java.sql.Connection,
                   java.sql.DriverManager,
                   java.sql.ResultSet,
                   java.sql.Statement" %>

<%!
  String title = "Database Test";
  String database = ""; 
  String sql = "SELECT title, url FROM Bookmarks ORDER BY title";
  Connection connection = null;
  Statement statement = null;
  ResultSet resultSet = null;
%>

<%
  try {
    database = application.getRealPath("/database/demobase");
  
    Class.forName("org.hsqldb.jdbcDriver");
    connection = DriverManager.getConnection("jdbc:hsqldb:file:" +
                                             database, "sa", "");
  
    statement = connection.createStatement();
    resultSet = statement.executeQuery(sql);
  }
  catch (Exception e) {
    out.print("Unable do make connection database<br>");
    out.print(e);
  }
%>

<html>
  <head>
    <title><%=title%></title>
  </head>

  <body>

  <h1><%=title%></h1>

  <h2>Bookmarks</h2>

  <ul>

    <% while (resultSet.next()) { %>
      <li><a href="<%=resultSet.getObject("url")%>"><%=
          resultSet.getObject("title")%></a></li>
    <% } %>
  </ul>

  </body> 
</html>

<%
  resultSet.close();
  statement.close();
  connection.close();
%>
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded 

  • 5 comments