Database-Backed Web Sites

Many web sites are database-backed web sites.

Databases

A database is a collection of (persistent) data, accessibile via software that can query and update the data.

There are many database vendors (Oracle, IBM, Informix, Microsoft) that sell zillions of database management systems (Oracle 8, DB2, Universal Server, SQL Server). You can download and install free (with restrictions) database systems on your computer too (e.g. Postgres, MySQL).

An Example

It helps to pick a particular setup and show examples that you can build, run, and experiment with on your own. I'll assume the following:

You should need only minor changes to use a different web server (such as Apache) or a different database (such as Postgres).

Setting up your web server

  1. Download and install Resin, if you haven't already.

  2. Locate the Resin configuration file (resin.conf) and make any changes you want. The default configuration should be fine if you are just playing around on your own computer.

  3. Start the web server and see that it is working by pointing your browser to "http://localhost:8080/". If you do not like the 8080, change the resin.conf file to run the server at port 80.

  4. Put a new JSP page in the documents directory called hello.jsp that looks like this:

    <html>
    <body>
    <p>Hello, two plus two is <%= 2 + 2 %></p>
    </body>
    </html>

    then point your browser to "http://localhost:8080/hello.jsp" to make sure the page gets served up.

Setting up the database server

  1. Download and install MySQL, if you haven't already. You'll probably installit in a directory called mysql. You will get subdirectories called bin (containing the server, client, and other tools), and data (containing further subdirectories for your databases).

  2. If you're installing MySQL, you're probably following the instructions that come with the documentation. Make sure you go through the section entitled "Post-installation Setup and Testing" (unless you're an expert at this kind of stuff).

  3. Run the database server, it will be a command like mysqld. By default, the server runs on port 3306.

  4. Note that you'll eventually need to stop the server, with a command such as mysqladmin -u root shutdown.

The MySQL Tutorial

Do the tutorial at http://mysql.com/documentation/mysql/bychapter/manual_Tutorial.html

Creating a database

Let's make a little database for a university. We'll name the database "university". If you already took the tutorial, you already know how to do this. You first startup the client, then enter

create database university;

Now execute the following

sampledata.mysql
# 
# Simple script to create a few tables and fill them with
# sample data.
#

# ----------------------------------------------------------------------------
# Person table
# ----------------------------------------------------------------------------

drop table if exists Person;

create table Person (
  id char(9) not null primary key,
  name varchar(100),
  birthdate date);
  
insert into Person (id, name, birthdate)
  values ('231342453', 'joey', '1988-04-22');

insert into Person (id, name, birthdate)
  values ('2894576503', 'svetlana', '1968-11-20');

insert into Person (id, name, birthdate)
  values ('111223333', 'irina', '1977-01-29');

insert into Person (id, name, birthdate)
  values ('987654321', 'raisa', '1967-02-16');

# ----------------------------------------------------------------------------
# Department table
# ----------------------------------------------------------------------------

drop table if exists Department;

create table Department (
  id char(4) not null primary key,
  name varchar(100),
  budget double,
  chair char(9) not null references Person(id));

insert into Department (id, name, budget, chair)
  values ('ELEC', 'Electrical Engineering', 60000.0, '987654321');

insert into Department (id, name, budget, chair)
  values ('PHIL', 'Philosophy', 100000.0, '111223333');

# ----------------------------------------------------------------------------
# Professor table
# ----------------------------------------------------------------------------

drop table if exists Professor;

create table Professor (
  id char(9) not null primary key references Person(id),
  degree varchar(10),
  department char(4) references Department(id));
  
insert into Professor (id, degree, department)
  values ('111223333', 'PhD', 'ELEC');

# ----------------------------------------------------------------------------
# Student table
# ----------------------------------------------------------------------------

drop table if exists Student;

create table Student (
  id char(9) not null primary key references Person(id),
  major char(4) references Department(id));
  
insert into Student (id, major)
  values ('231342453', 'ELEC');

You can check that the database was succcessfully created and loaded:

mysql> show tables;
+----------------------+
| Tables_in_university |
+----------------------+
| department           |
| person               |
| professor            |
| student              |
+----------------------+
4 rows in set (0.00 sec)

mysql> select * from person;
+-----------+----------+------------+
| id        | name     | birthdate  |
+-----------+----------+------------+
| 231342453 | joey     | 1988-04-22 |
| 289457650 | svetlana | 1968-11-20 |
| 111223333 | irina    | 1977-01-29 |
| 987654321 | raisa    | 1967-02-16 |
+-----------+----------+------------+
4 rows in set (0.05 sec)

Now let's see how to access this data from a web application.

Informing the Web Server About the Database

While it is possible to put all information about the database, including the database name, port, user name and password directly into a web page, doing so is bad for maintainability and security reasons.

The best thing to do is to tell Resin about your database by placing the following element inside the <caucho.com> element in the Resin configuration file:

<resource-ref>
  <res-ref-name>jdbc/university</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <init-param driver-name="com.caucho.jdbc.mysql.Driver"/>
  <init-param url="jdbc:mysql_caucho://localhost:3306/university"/>
  <init-param user=""/>
  <init-param password=""/>
</resource-ref>

You'll want to fill in the actual database user name and password, and make other adjustments specific to your own site, of course.

A sample page that issues a query and shows the result

Here is the source code of a JSP page that connects to the university database, executes a query, writes the result to an HTML table, and disconnects.

dbexample.jsp
<%@ page language=java %>
<%@ page import='java.sql.*' %>
<%@ page import='javax.sql.*' %>
<%@ page import='javax.naming.*' %>

<html>
<body>

<p>Here is a table from the university database</p>

<%
Context env = (Context)new InitialContext().lookup("java:comp/env");
DataSource source = (DataSource)env.lookup("jdbc/university");
Connection conn = source.getConnection();

try {
    Statement statement = conn.createStatement();
%>

<table border="1">
<tr>
<%
    ResultSet rs = statement.executeQuery("select * from Department");
    ResultSetMetaData metaData = rs.getMetaData();
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        out.print("<th>" + metaData.getColumnName(i) + "</th>");
    }
%>
</tr>
<%
    while (rs.next()) {
%>
<tr>
<td><%= rs.getString(1) %></td>
<td><%= rs.getString(2) %></td>
<td align="right"><%= rs.getDouble(3) %></td>
<td><%= rs.getString(4) %></td>
</tr>
<%
    }
%>
</table>

<p>Now here is the result of a more complex query</p>
<table border="1">
<tr>
<%
    statement = conn.createStatement();
    rs = statement.executeQuery(
            "select d.id, d.name, d.budget, p.name "
            + "from Department d, Person p "
            + "where d.chair = p.id "
            + "and d.budget > 500.0");
    metaData = rs.getMetaData();
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        out.print("<th>" + metaData.getColumnName(i) + "</th>");
    }
%>
</tr>
<%
    while (rs.next()) {
%>
<tr>
<td><%= rs.getString(1) %></td>
<td><%= rs.getString(2) %></td>
<td align="right"><%= rs.getDouble(3) %></td>
<td><%= rs.getString(4) %></td>
</tr>
<%
    }
} finally {
  conn.close();
}
%>
</table>

</body>
</html>

Yikes! I'm Just a Web Designer! This Looks Too Technical!

Well, let's look at what's important and what you really need to know first.