Java and Database Connectivity
    Author and presenter: Simon
    Brooke.
    The full text of this presentation is online at <URL:
    http://www.jasmine.org.uk/~simon/bookshelf/papers/inet2001/jdbc/>
    Changes to the presentation since your
    handouts were printed are highlighted like this.
    
      Simon Brooke, 21
      Main Street, Auchencairn, Scotland.
    
    
    What you're going to achieve today
    
      - Understand (a bit about) Java
- Understand (a bit about) Relational databases
- Build a Web-delivered database application
- Understand enough to know where to start when you get
      home
Some of you will know some of this already. Please be
    patient while I cover the bits you know, someone else may
    not.
    
    How we're going to get there
    
      - The morning, mostly talking
- This afternoon, mostly doing it.
- As I write this, I'm expecting we're going to be able to
      use the terminal room in the afternoon, but I don't have
      confirmation of this. I'm designing this course to be
      hands-on. If it can't be, we may have a tricky
      afternoon!
    Breaks
    
      - Coffee 10:30 (I hope to be about the end
      of 'getting started with Java)'
- Lunch 12:30 (I hope to be about the end
      of 'getting started with JDBC'
- Coffee 3:30 (I hope to be about the end
      of 'building a Web based application')
- We're supposed to end at 5:30.
Nearest WCs, how to get to coffee?
    
    Before we start: what do you know
    We've got a lot of ground to cover Just so I can know which
    bits to concentrate on and which bits to skip, what do you know
    about... 
    
      
        
          |  | nothing | a little | can do it | expert | 
        
          
          | HTML |  |  |  |  | 
        
          | Java |  |  |  |  | 
        
          | SQL |  |  |  |  | 
      
    
    
    Before we start: Namespace
    
      - A context in which there are things with names
- Each thing in the namespace has a different name
- You can address a thing in the namespace just by using
      its name
- 
        Examples 
        
      
[get participants to write their names
    on bits of paper. Make sure there are not two in the class with
    the same name. If there are, get them to add something to their
    names to disambiguate]
    
    Background to the technology
    
    
    The Internet and the Web
    Open, heterogenous network of networks, carrying distributed
    hypertext
    
      - Open:
- the standards are published, and are not protected by
      patents, non-disclosure agreements, and so on - anyone can
      copy them.
- Heterogenous:
- the standards aren't based on the facilites of any one
      proprietary sort of computer - any computer can be
      connected
- Networks of networks:
- not every computer everywhere has to be able to connect
      to the same network standards, provided that the networks
      themselves can intercommunicate.
    A brief history of Distributed Hypertext
    or 'none of this is new' part one
    
      - Project
      Xanadu, Ted Nelson 1960
- 
        Distributed hypertext over heterogenous networks 
- TCP/IP, Xerox PARC, 1970s
- 
        Transmission of data over unreliable networks of
        networks 
- HTML, Tim
      Berners-Lee, CERN, 1990
- 
        Distributed hypertext over heterogenous networks - much
        simpler than Xanadu 
    Forms in HTML
    
      - As well as pages of text, HTML provides mechanisms for
      forms
- Containing INPUT elements
- Associates a name with a
      value
- So each form is a namespace
    What is Java?
    
      - Eye candy on Web pages?
- An interesting language for Web enabled
      applications?
- The future of software engineering?
    Java: history and background
    or 'none of this is new' part two
    
    Brief history of programming languages
    
      - LISP, John McCarthy,
      1959
- BCPL: Martin Richards, Cambridge University, 1969
- C: Thompson & Richie, Bell Labs, 1972
- Smalltalk,
      Goldberg, Kay and others, Xerox PARC, 1973
- Oak: James Gosling, Sun Microsystems, 1990
- Java: James
      Gosling et al, Sun Microsystems 1995
- JDBC: Sun Microsystems 1996
    LISP, John McCarthy,
    1959
    
      - Automatic memory management and Garbage Collection
    BCPL: Martin Richards, Cambridge University, 1969
    
      - low level typeless language
- compiled to compact interpreted ('CINT') code, hardware
      independent.
- standard library
- CINT code interpreter is 'virtual machine'.
    C: Thompson & Richie, Bell Labs, 1972
    
      - derived directly from BCPL but compiles to machine
      code
- used to write the UNIX operating system
- became widely used
- [horrible] 'object oriented' extensions - C++ and
      Objective C.
    Smalltalk,
    Goldberg, Kay and others, Xerox PARC, 1973
    
      - Automatic memory management
- Everything is an object
- Class inheritance
- Interactive graphical user interface
    Oak: James Gosling, Sun Microsystems, 1990
    
      - Targeted at consumer electonics products
- Like LISP, memory management is automatic
- Like SmallTalk, (almost) everything is an
      object
- Like BCPL, compiles to hardware independent code
- Only the syntax is like C++
    Java: James Gosling
    et al, Sun Microsystems 1995
    
      - OAK plus Web browser renamed 'Java' and launched publicly
      by Sun
    JDBC: Sun Microsystems 1996
    
      - Abstract database connectivity extensions to the standard
      Java classes
    What is SQL
    
      - A proprietary database system sold by Microsoft?
- An obscure and difficult language used by database
      gurus?
- A more or less universal way to talk to databases?
    SQL: History and Background
    or 'none of this is new' part three
    
      - Theory of Relations from Mathematics
- Ted Codd, 1970 - definition of relational databases
- SEQUEL, IBM, mid-70s - precursor to SQL
- 1979, Oracle adopts SQL
- 1981, Ingres adopts SQL
- ANSI SQL, 1982 onwards, first standard 1986
Standard used by JDBC is ANSI 92
    
    The big question: How do you pronounce it?
    
      - It's not cool to say 'S Q L'
- Serious IBM and Oracle type people say
      'Sequel'
- Some less serious Oracle people say
      'Squirrel'
- Some Postgres (pg_sql) people say 'Pig
      Squeal'
    Types of database systems
    
      - 
        SQL is the language of Relational
        databases; other database models include 
          - Hierarchical databases
- Object-Oriented databases
 Been around a long time, and have their merits, but none
        has been so generally useful as the Relational model. 
- Most database systems are relational database
      systems
- Most relational database management systems (RDBMS)
      understand SQL
- Most, unfortunately, also include proprietary
      extensions.
    In summary:
    Java, SQL and Internet technology
    
      - TCP/IP: vendor independent network architecture
- HTML: vendor independent document architecture
- HTTP: vendor independent distribution architecture
- JAVA: vendor independent application architecture
- JDBC: vendor independent database connectivity
- SQL: vendor independent database interaction
There are proprietary, vendor specific ways of doing all
    these things...
    
    Getting started with Java
    
      - A bit about 'Object Orientation'
- Main features of the language
- A bit about syntax
- Using packages
- The classpath and using archives
    A bit about Object Orientation (i): taxonomy
    
      - A bird is an animal
- A fish is an animal
- A bird has some properties and behaviours that fish don't
      have
- A fish has some properties and behaviours that birds
      don't have
- There are some properties and behaviours that all animals
      have
- That plants, for example, don't have
Draw it - extend it.
    
    A bit about Object Orientation (ii): languages
    
      - Object Oriented languages represent taxonomies
- 
        Classes describe groups of things 
        
          - which share the same properties and the same
          behaviour
 
- 
        An Object has all the behaviours described
        by its class 
        
          - 
            And by its class's 'superclass' 
            
              - And by the superclass's superclass
 
 
- We describe behaviours by adding
      methods
- We specialise behaviours by specialising methods
    Main features of the language
    
      - 
        Java is an Object Oriented language 
        
          - Almost
- 
            Primitive data items 
            
              - ints
- floats
- doubles
- chars
- etc...
 are not objects
- Most of the time this does not matter
 
- With strong typing
- Dynamic memory management
- C-like syntax
- Compiled to instructions for a portable virtual
      machine
    A bit about syntax: example java source
package uk.co.weft.clock;
import java.lang.*;     // import general utility classes
import java.awt.*;      // for graphics handling
/** A subclass of Hand which is just a blob rotating at a fixed
 *  length about the centre. All the mechanism for moving the 
 *  hand is in Hand.
 *
 *  @author Simon Brooke (simon@jasmine.org.uk)
 *  @version $Revision: 1.9 $
 */
public class BlobHand extends Hand
{
    int radius;         // the radius of my blob
    /** initialise myself; in addition to the things hands have
     *  generically, I have a radius */
    public BlobHand( int l, HandDriver d, int r)
    {
    super( l, d);
    radius = r;
    }
    /** just a blob round my end position */
    public void paint( Graphics g)
    {
        g.setColor( colour);
        g.fillOval( end.x - radius, end.y - radius, 
            2 * radius, 2 * radius);
    }
}
    
    A bit about syntax: declaring and importing packages
package uk.co.weft.clock;
    This is the package this class is in
import java.lang.*;     // import general utility classes
import java.awt.*;      // for graphics handling
    These are the packages it uses
    
    A bit about syntax: comments
package uk.co.weft.clock;
import java.lang.*;     // import general utility classes
import java.awt.*;      // for graphics handling
    
      - Anything on a line following two slash characters
      (//) is a comment
- Nothing special about this kind of comment
/** A subclass of Hand which is just a blob rotating at a fixed
 *  length about the centre. All the mechanism for moving the 
 *  hand is in Hand.
 *
 *  @author Simon Brooke (simon@jasmine.org.uk)
 *  @version $Revision: 1.9 $
 */
    
      - Anything between slash-star (/*) and
      star-slash (*/) is a comment
- 
        If it starts with slash-star-star (/**) it's ajavadoccomment
          - javadocis a program which automatically
          generates documentation for Java classes and packages by
          associating- /**comments with the
          declaration that immediately follows them
- If there isn't a declaration after a /**comment javadoc will ignore it
- @authorand- @versionare
          special tokens understood by javadoc
- $Revision ... $is a special token used
          understood by the version control system I use
 
    A bit about syntax: declaring a class
public final class BlobHand extends Hand
{
    int radius;         // the radius of my blob
    
      - 
        publicmeans that any other class in any other
        package may use this class
          - it might be protected(only usable by
          other classes in the same package)
- or private(only usable by other classes
          in the same file)
 
- 
        finalmeans that no class may specialise
        ('extend') this class
          - most classes are not final
 
- classmeans it's a class
- BlobHandis the name of this class
- extends Handmeans that a BlobHand is a kind
      of Hand, and inherits all Hand's behaviours and
      properties
- radiusis an instance variable of
      BlobHand. Every instance (object) in the BlobHand class has a
      radius. It doesn't have to be the same radius.
- A public class must be declared in a file whose name is
      the same as the name of the file (with the extension '.java'.
      So the class BlobHandmust be declared in a file
      calledBlobHand.java
    A bit about syntax: declaring a constructor
    A constructor is a special method called to
    construct an instance of a class. It has the same name as the
    class, and no return type declaration
    /** initialise myself; in addition to the things hands have
     *  generically, I have a radius */
    Again, a 'javadoc' comment. This one documents this
    constructor.
    public BlobHand( int l, HandDriver d, int r)
    This constructor takes three arguments, respectively an
    int, a HandDriver, and another
    int. An int is a primitive data type
    which is not an object; a HandDriver is an object
    whose class is either HandDriver or some subclass of
    HandDriver
    {
        super( l, d);
    The first thing this constructor does is to pass it's first
    two arguments 'up the tree' to its superclass's constructor,
    which knows how to deal with them.
        radius = r;
    }
    The superclass doesn't have a radius, so it can't know how
    to deal with it. So initialise it here.
    
    A bit about syntax: declaring a method
    /** just a blob round my end position */
    public void paint( Graphics g)
    {
        g.setColor( colour);
        g.fillOval( end.x - radius, end.y - radius, 
            2 * radius, 2 * radius);
    }
    
      - 
        Methods are the way we describe the behaviour of objects.
        Here is a methd called paintwhich describes
        how aBlobHandpaints itself on aGraphicsobject.
          - It calls a method setColorof theGraphicsobject to set the colour it
          wants.
- It calls a method fillOvalof theGraphicsobject to draw a filled circle at
          its end position
 
- publicmeans that any other object can call
      this method
- voidmeans that this method doesn't return
      any value
    Let's see that happen...
     
    
      - 
        Yes, it's an applet 
        
          - An applet is a small, secure, network portable
          component
- Requires applet capable browser
- Unless very small takes a long time to download
 (If you don't have Java on your browser, but you do
        have graphics, you'll see a static image)
- The hour and minute hands are BatonHands - a
      different subclass of Hand
- The bright blue second hand is a
      BlobHand
- Both inherit the ability to go round the dial from
      Hand
     
    
    Using packages
    
      - Packages are bundles of Java functionality
- The core of Java is the package
      java.lang
- Other packages with names starting java.are
      parts of the standard Java distribution
- 
        Third party organisations which create packages should use
        the elements of their domain name in reverse order as
        prefix 
        
          - We're 'weft.co.uk' so our package names start
          uk.co.weft.
- So the clock components are in
          uk.co.weft.clock
 
- This way you can mix components from anywhere without
      risk of name clashes
    The classpath and using archives
    How does Java find the classes it needs?
    
      - 
        Source files are compiled into class files 
        
      
- 
        Class files are kept in directories whose path structure
        reflects the package name 
        
          - uk.co.weft.clock.BatonHandis stored in- uk/co/weft/clock/BatonHand.class
 
- 
        The directories may be packed up 
        
          - into 'java archives' ('JAR files')
- or ZIP archives
 
- A special environment variable called
      CLASSPATHtells Java where to look for these
      directories and archives
    Java: Reprise
    
      - An object-oriented language with C-like syntax
- A portable virtual machine
- Classes of objects grouped into packages
- Packages often distributed as JAR or ZIP files
This only scratches the surface - there is masses more to
    Java but we won't have time today.
    
    Getting started with SQL
    
      - What is a Relational Database?
- What is a Table?
- Example tables
- Basic operations on a database
- Relationships
    What is a Relational Database?
    
      - A namespace in which
      names are associated with
      tables.
- With (potentially) relationships between
      the tables
    What is a Table?
    
      - A set of rows (or a set of columns, depending on how
      you look at it)
- Each row is a namespace
- Each namespace contains the same names
- Each name is associated with the same
      kind of thing in every namespace
Representing a set of things in the domain
    
    Example table one: WORKSHOP
    
      
        
          
          |  | Columns | 
        
          | Workshop | Tutor | Title | Venue | Date | 
        
          | Rows | 2 | Simon Brooke | Java and Database Connectivity | small | 07-17-2000 | 
        
          | 7 | Simon Brooke | Moving to XML | small | 07-18-2000 | 
        
          |  | Primary key | 
      
    
    
    Example table two: ATTENDEE
    
      
        
          | Attendee | Name | Age | Sex | Country | 
        
          | 1 | Jon Smith | 37 | M | UK | 
        
          | 2 | Jane Doe | 42 | F | US | 
      
    
    
    Example table three: VENUE
    
      
        
          | Venue | Name | Capacity | 
        
          | small | The small room | 20 | 
        
          | mid | The middle-sized room | 60 | 
        
          | main | The auditorium | 2000 | 
      
    
    
    Basic operations on a database
    
      - Create
- creates tables
- Insert
- creates rows in tables
- Select
- selects information from rows in tables
- Update
- changes rows in tables
- Delete
- deletes rows from tables
- Drop
- drops tables
    Create
    Creates a new table (and other things...)
    create table WORKSHOP 
    (
    Workshop int not null primary key,
    Tutor varchar( 40) not null,
    Title varchar( 80) not null,
    Venue varchar( 8)
    );
    
    
    Insert
    Inserts a new row (or rows) into an existing table
    insert into WORKSHOP 
    (Workshop, Tutor, Title) 
        values ( 4, 'Gordon Howell', 
         'E-Business in Practice');
    
    
    Select
    Selects information from rows in tables
    select Title, Venue from Workshop 
     where Tutor = 'Simon Brooke';
    
    We'll come back to this...
    
    Update
    Changes values in an existing row (or rows) in an existing
    table
    update WORKSHOP 
       set Venue = 'mid' 
     where Tutor = 'Simon Brooke';
    
    Delete
    Deletes one or more rows from an existing table
    delete from WORKSHOP 
      where Tutor = 'Simon Brooke';
    delete from WORKSHOP;
    
    Drop
    Deletes an existing table entirely
    drop table workshop;
    
    Relationships: One to many (i)
    What's the relationship between the workshop and the
    venue?
    Easy to describe:
     
 
    
      - The workshop is in the venue
- The venue accomodates the workshop
One to many:
    
      - Each workshop is in one venue;
- Each venue can house many workshops (but not all at the
      same time, of course)
    Relationships: One to many (ii)
    Easy to represent:
    the table at the many end has a column (a foreign
    key field) which holds the value of the
    primary key field at the one end.
    
    Relationships: Many to many (i)
    What's the relationship between the attendee and the
    workshop?
    Easy to describe:
     
 
    
      - The attendee participates in the workshop
- The workshop enlightens the attendee (we
      hope)
Many to Many
    
      - Each workshop has many attendees (we hope)
- Each attendee may attend more than one workshop (how many
      of you are coming tomorrow)?
    Relationships: Many to many (ii)
    Hard to represent
    
      - We can't have a column in the workshop table for every
      attendee, because we don't know how many there will be
- We can't have a column in the attendee table for every
      workshop, because we don't know how many there will be...
      (actually we could in this case, but not as a general
      rule).
    Link Table
    We need a linking table
     
 
    Attendance:
    
      - One attendee may attend in many attendances
- One workshop may have many attendances
- 
        Each attendance has 
        
          - one attendee
- one workshop
 
      
        
          | Workshop | Attendee | 
        
          | 2 | 1 | 
        
          | 4 | 2 | 
        
          
          | 7 | 1 | 
        
          | 7 | 2 | 
      
    
    
    Link (or 'linking') table
    
      - Doesn't represent things which really exist in in the
      domain
- Usually does not have a primary key
- Is a huge convenience!
    Join
    Once we have relationships, we can join tables to produce
    more useful data.
    
      - 
        Where does Jane Doe have to go, and on which days? 
    select VENUE.Name, WORKSHOP.Date
      from ATTENDEE, ATTENDANCE, WORKSHOP, VENUE
     where ATTENDEE.Name = 'Jane Doe'
       and ATTENDEE.Attendee = ATTENDANCE.Attendee
       and ATTENDANCE.Workshop = WORKSHOP.Workshop
       and WORKSHOP.Venue = VENUE.Venue
  order by WORKSHOP.Date;
    
- 
        Who is coming to Simon Brooke's workshops? 
    select distinct ATTENDEE.Name 
      from ATTENDEE, ATTENDANCE, WORKSHOP
     where ATTENDEE.Attendee = ATTENDANCE.Attendee
       and ATTENDANCE.Workshop = WORKSHOP.Workshop
       and WORKSHOP.Tutor = 'Simon Brooke';
    
    SQL: Reprise
    
      - Table:
- 
        
          - a set of similar namespaces (rows)
- representing a kind of thing in the domain
- 
            each namespace (row) represents one thing of this kind 
            
              - Like objects in a class... almost.
 
 
- Primary key:
- 
        
          - a column in a table in which each value is distinct
          from every other.
- makes the table into a namespace of rows
- not every table has one
 
- Foreign keys
- 
        
          - a column in a table whose values are values from the
          primary key column in another table
- not every table has one
- some tables have more than one
 
- Join
- 
        
          - A select statement which joins two or more
          tables
- Usually in ways that represent predetermined
          relationships
- If mis-constructed (e.g. 'cross-product joins') can
          go horribly wrong
- Complex joins can be expensive to compute.
 
    Other things in SQL which we may use
    
      - Views
- 
        named joins 
        
          - can be selected from and joined just like tables
- can't be written to
- not supported by all databases
 
    create view myview as select ...
- Transactions
- Groups of statements which are executed together, such
      that if any one of them fails, the effects of all of them can
      be reversed.
- 
    begin
    delete from attendance where workshop = 7;
    delete from workshop where workshop = 7;
    commit;
- Permisssions
- 
        
          - control who can do what to what
- very important, particularly for Web databases
- not supported by all databases
 
    grant select, insert, update, delete 
       on venue 
       to simon;
    revoke update, delete 
        on attendance
      from simon;
    revoke insert, update, delete 
        on venue, attendee, attendance 
      from public;
    
There's lots more in SQL but we won't have time today.
    
    Getting started with JDBC
    
      - What is JDBC
- Configuring JDBC
- Programming with JDBC
    What is JDBC (i)
    'Java Database Connectivity'
    
      - In many languages, different code is needed to talk to
      different databases
- JDBC provides an abstraction layer
- The same code can be used with all databases
- Provided they understand ANSI 92 SQL
    What is JDBC (ii)
    
      - Provided in a package called 'java.sql'
- Standard part of Java 1.2 and subsequent API
      specifications
- No special jar file needed
    Configuring JDBC
    
      - Where is the database?
- The URL
- How do we talk to the database?
- The Driver
- Who are we?
- The username and password
    The URL
    
      - A special format URL describes where the database
      is.
- 
        Actually, the URL format differs from driver to driver, for
        example: 
        
          - 
          jdbc:postgresql://gododdin:5432/smeq
- 
          jdbc:oracle:thin:@gododdin:1521:smeq
- jdbc:odbc:smeq
 
- Read the documentation that comes with your driver!
    The Driver
    
      - A class in a package which you load into your Java system
      which knows how to talk to your particular database
- 
        Four types 
        
          - JDBC-ODBC Bridge Driver talks to an
          ODBC connection using largely non-Java code.
- Native API, Partly Java uses foreign
          functions to talk to a non-Java API; the non-Java
          component talks to the database any way it likes
- Net Protocol, pure Java talks to a
          middleware layer over a network connection using the
          middleware's own protocol
- Native Protocol, pure Java talks
          directly to the RDBMS over a network connection using an
          RDBMS-specific protocol
 
    The username and password
    
      - Used to do database-level security (a good thing).
- Not supported by lighter-weight databases.
    Exercise period (i)
    Use the supplied SQLExec class to talk to the supplied
    WORKSHOPS database.
    
    Programming with JDBC
    
      - Importing the Package
- Registering the driver
- Getting a Connection
- Creating a Statement
- Getting a ResultSet
- Putting it all together... tidily...
- Gotchas
    Importing the Package
import java.sql.*;
    
      - The name of the JDBC package is java.sql
- 
        It's usually simplest to import everything from it 
        
      
- Every class that makes use of JDBC stuff must include
      this import statement.
    Registering the Driver
    
      - Need a driver name
- Just loading the class into the Java Virtual Machine
      registers it.
    Class.forName( driverName)
    
    Getting a Connection
    
      - Need a URL, a username and a password
- Might throw an exception
- No simple means of working out what the exception
      means
    Connection c;
    try
        {
            c = DriverManager.getConnection( url, user, pass);
        }
    catch ( SQLException e)
        {
            out.println( "Could not connect to database " + url);
            out.println( "Does it exist? Are you authorised?");
        }
    
    Creating a Statement
    Before you can talk to the database, you need a
    statement
        Statement stt = c.createStatement();
    
    Getting a ResultSet
    You get hold of the data by asking the statement for a
    ResultSet
    ResultSet r = s.executeQuery( q);
    while ( r.next())
    {
        // do things with the row
    }
    If there's time, show examples of doing
    things with ResultSets, e.g. DataMenuWidget.getOptions()
    
    Putting it all together: untidily
        ResultSet r =
            DriverManager.getConnection().createStatement().executeQuery(
                "select * from ATTENDEE");
        while ( r.next())
        {
            // do things with the row
        }
    Don't do this!
    
    Putting it all together: tidily
        Connection c = DriverManager.getConnection( url, user, pass);
        Statement s = c.createStatement();
        String q = "select * from ATTENDEE";
        ResultSet r = s.executeQuery( q);
        while ( r.next())
        {
            // do things with the row
        }
        s.close();          // close the statement
        c.close();          // close the connection
    
    Using resources: Why be tidy?
    
      - 
        You don't need to be tidy 
        
          - Doesn't matter for small or non-critical
          programs
- Connections will be reclaimed by the garbage
          collector if you don't expicitly close them
 
- 
        But 
        
          - You don't know when garbage collection will
          happen
- It might happen before you've finished with your
          result set
- It might not happen for a long time, and you might be
          left with many open sessions which will overload your
          database server
 
    Using resources: Connection pooling
    
      - Setting up connections can be compute-expensive
- Good to re-use them if you can
- More about this later
    Transactions with JDBC
    
      - Remember, transactions aren't supported by all
      databases!
- JDBC can't make transactions happen in databases which
      don't support them
        Connection c = DriverManager.getConnection( url, user, pass);
        c.setAutoCommit( false)
        // Do some things which need to be done together
        c.commit();     // commit them
        // Do some more things which need to be done together
        c.commit();     // commit them
        c.close();
    
    
    Gotchas
    
      - A ResultSet becomes invalid when the next ResultSet with
      the same statement is asked for
- A ResultSet becomes invalid when its Statement is
      closed
- A Statement becomes invalid when it's connection is
      closed
- If you don't explicitly release connections, you will run
      out of resources
    Exercise period (ii)
    
      - 
        In groups 
        
          - Design a database for recording meetings.
- 
            Your database should be able to record 
            
              - 
                Who is coming to any given meeting 
                
                  - Whether their attendance is important
- Whether they have said whether they can
                  come
 
- What meetings any given person is attending
- What meetings are being held in any given
              venue
 
- Think about other things you might want a meetings
          system to do.
 
- Do your design on paper first
Try to get at least one person in each
    group who is going to be at tomorrow's XML course - or, at
    worst, don't let the XML course people all bunch up into one
    group. Try to encourage groups to do their own analysis and not
    copy each others'. Ideally I want to end up the day with at
    least two quite different databases.
    
    Building a (Web based) Application
    
      - 
        Servlets 
        
          - Server-side Java components which handle particular
          requests
- Analogous to CGI
- More or less analogous to ASP
 
- The Jacquard
      Toolkit
- 
        Other free Servlet toolkits 
        
      
    Jacquard toolkit (i)
    
      - a Java language toolkit for the rapid development of
      data-driven web enabled applications.
- I wrote (most of) it, so I'm not unbiased about it
    Jacquard toolkit (ii): htform
    
      - 
        uk.co.weft.htform package provided in file
        htform.jar 
        
          - Servlet
- TableWrapperForm
- Widgets
 
    Jacquard toolkit (iii): dbutil
    
      - 
        uk.co.weft.dbutil package provided in file
        dbutil.jar 
        
          - More database abstraction
- Stores
- Contexts (namespaces)
- Connection pooling
 
    Jacquard toolkit (iv): domutil
    
      - 
        uk.co.weft.domutil package provided in
        file domutil.jar
        
          - Generation of DOM compliant document objects
- DocumentGenerator
- ElementGenerator
- CachedPage and friends
 
    Using Jacquard
    
      - 
        To create a form to edit and update data in a table 
        
          - Specialise TableWrapperForm
- If necessary, add extra widgetSets
- Add appropriate widgets
 
- 
        To create a means of selecting data to edit 
        
      
    Example Jacquard Form
import javax.servlet.*;
import javax.servlet.http.*;
import uk.co.weft.dbutil.*;
import uk.co.weft.htform.*;
import java.util.Stack;
/** an example form which allows you to enter and manipulate WORKSHOP
 *  records */
public class WorkshopForm extends TableWrapperForm
{
    /** Initialise me. Principally, set up my widgets */
    public void init( Context config)
        throws InitialisationException
    {
        table = "WORKSHOP";        // set up my table
        keyField = "Workshop";     // and my primary key
        addWidget( new 
            Widget( "Tutor", "Tutor", 
            "The Tutor of this workshop"));
                // add a simple text widget for the
                // tutor's name
        Widget w = addWidget( new 
            Widget( "Title", "Title", 
            "The title of this wokshop."));
                            // another simple text input fo the title  
        w.setSize( 80);     // which is extra long...
        w.setMandatory( "You must supply a title for this wokshop");
                // and which you must complete before proceding
        addWidget( new 
            SimpleDataMenuWidget( "Venue", "Venue", 
                  "The venue for this workshop",
                  "VENUE", "Venue", "Name"));
                // a menu constructed from another
                // table for the venue
    
        addWidget( new DateWidget( "Date", "Date", 
                   "The date of this workshop"));
                // a date, oddly enough!
        addWidget( new 
           LinkTableWidget( "ATTENDANCE", "Attendees",
                 "People who are expected to take part in this workshop.", 
                 false, 7,
                 "WORKSHOP", "ATTENDEE", "Workshop", 
                 "Attendee", "Name"));
                                // and a link-table widget to set up attendees
        super.init( config);    // finally do my superclass configuration
    }
    /** When a workshop is deleted from the database, we don't want to
     *  leave orphanced attendances hanging about. So drop my
     *  attendance links before dropping me! Note
     *  that you don't need methods like this if the database supports
     *  proper referential integrity checks and triggers - which good
     *  databases do.
     *
     *  @param context the context which contains the identifier of
     *  the record to be dropped
     *  @exception throws DataStoreException if delete fails.
     */
    protected void drop( PageContext context)
        throws DataStoreException, ServletException
    {
        Stack drops = new Stack();
        Object id = context.get( keyField);
        drops.push( "delete from ATTENDANCE " + 
                    "where ATTENDANCE.Workshop = " +
                    id.toString());
                                // it's a stack, so push them in reverse order
        super.drop( context, id, drops);
    }
}
    
    Exercise period (iii)
    
      - 
        In your groups, write a set of Java servlets to allow your
        database to be browsed and edited. 
        
          - Agree among yourselves who will do what.
- As well as writing the servlets you will have to get
          them integrated into your Servlet engine.
 
- Look at the servlets in the uk.co.weft.eventpackage. They will give you a good start!
    And now, the end is near...
    
      - What have you achieved?
- Why is this good technology?
- What should you do next?
    What have you achieved?
    
      - Some understanding of SQL
- Some understanding of Java
- Some understanding of JDBC
- I hope, a working application
    Why is this good technology? (ii)
    
      - 
        Your application will work on any platform which supports
        Java 
        
          - Windows
- UNIX
- AS/400
- Macintosh
- Others
 
- 
        Talking to any database which understands SQL 
        
          - Oracle
- Postgres
- Informix
- Sybase
- SQL Server
- Many others
 
- 
        Accessible by any client which understands HTML 
        
          - Desktop PCs
- Notebooks
- Handheld devices
- Mobile phones
- Televisions (with WebTV, for example)
 
    Why is this good technology? (ii)
    
      - You are not locked in to any individual vendor's
      products
- You are not locked in to any individual hardware
      platform
    What should you do next?
    
      - Enjoy the conference!
- Study the resources (coming up)
- 
        When you get home 
        
          - 
            Develop a small, manageable application which will be
            genuinely useful 
            
              - A diary system, like
              uk.co.weft.event, is good
- The meeting system we talked about would be
              good
- A room booking system would be good
 
- Evaluate it
 
- Think about what you can do next
    Resources
    Java
    
      - 
        
      
- Java(tm) Home Page: http://java.sun.com/
- Java home page at Sun.
- news:comp.lang.java.databases
- Newsgroup for JDBC related issues - recommended
- news:comp.lang.java.programmer
- Newsgroup for general Java releated issues - a bit noisy
      but often useful.
- 
        Documentation
          - 
            
          
- Java Documentation (primary site): http://www.javasoft.com/docs/index.html
- This is the source.... (but if you're doing it
          properly you need to download a local copy).
- Download The Java Tutorial: 
          http://java.sun.com/docs/books/tutorial/information/download.html
- This is where to download it from.
- Java in a Nutshell, 2nd Edition : A Desktop Quick
          Reference for Java Programmers: http://www.oreilly.com/catalog/javanut2/
- An enormously useful reference book, but...
- Java Examples in a Nutshell : A Companion Volume to
          Java in a Nutshell: http://www.oreilly.com/catalog/jenut/
- ... if you're learning Java, the examples book is
          actually far more useful because it gives masses of
          example code, neatly laid out and annotated, to work
          through. Strongly recommended.
- Java Programmers FAQ: http://www.afu.com/intro.html
 
- 
        Tools
          - 
            
          
- 
            Free/Open Source tools
              - 
                
              
- Java-Linux: http://www.blackdown.org/
- Home page for the team responsible for porting
              Java to Linux.
- TYA -- Open Source Java JIT compiler: http://www.dragon1.net/software/tya/
- 'Just In Time' compilers can substantially
              improve the performance of Java programs at run time.
              TYA is a '100% unofficial' JIT-compiler designed as
              an add-on to Randy Chapman's port of JDK 1.0.2 for
              Linux
 
- (x86). Later I have added some changes in TYA
              code for working together with the newer 1.1.x ports
              by Steve
 
- Welcome to Java WebIDE!: http://www.chamisplace.com/prog/javaide/
- Weird but interesting. A complete Java Integrated
              Development Environment implemented at server-side
              and delivered as a Web page...
- RMI-JDBC - JDBC to remote hosts: http://dyade.inrialpes.fr/mediation/download/
- Freeware JDBC middleware layer from INRIA.
 
- 
            Commercial tools
              - 
                
              
- Simplicity for Java Homepage: http://www.datarepresentations.com/
- The most interesting commercial Java IDE I've yet
              seen and the only one I would actually pay money for.
              100% pure Java; free evaluation download.
- Welcome to NetBeans: http://www.netbeans.com/index.html
- Another interesting commercial Java IDE written
              in 100% pure Java. Free evaluation download.
- IBM VisualAge for Java: Download: 
              http://www.software.ibm.com/ad/vajava/download.htm
- IBM's Java IDE
- Visual Café 3.0: 
              http://www.symantec.com/region/uk/product/vcafe/
- Probably the best of the mainstream commercial
              IDEs
- Metamata Home Page: http://www.metamata.com/
 
 
- 
        Resources
          - 
            
          
- Gamelan: Earthweb's Java Directory: http://www.gamelan.com/
- An onlline searchable resource of both freeware and
          commercial Java components. Useful, but these days
          overloaded and slow.
- www.jrefinery.com: http://www.jrefinery.com/
- Algorithmics in Java: 
          http://students.ceid.upatras.gr/~papagel/project/contents.htm
 
- 
        Servlets
          - 
            
          
- 
            Servlet Engines
              - 
                
              
- Locomotive: http://www.locomotive.org/
- Enhydra: http://www.enhydra.org/
- Bull EJB: home page: http://www.bullsoft.com/ejb/
- Caucho Technology Products: 
              http://www.caucho.com/products/resin/index.html
 
- The Java Apache Project: http://java.apache.org/
- The best way to serve servlets with Apache.
- Servlet Central: The Server-side Java Magazine: http://www.servletcentral.com/
- An online newsletter aiming to provide quality
          information for servlet developers. On the whole, so far,
          seems good.
- View Source: Java Servlets in Netscape Enterprise
          Server: 
          http://developer.netscape.com/viewsource/kadel_servlet.html
- Live Software, Inc.: http://www.livesoftware.com/
- Vendors of a Servlet server 'JRun', and, possibly
          more importantly for us, a ColdFusion interpreter as a
          Java Servlet
- Purple Servlet FAQ by Alex Chaffee: http://www.purpletech.com/java/servlet-faq/
- Java Apache Project: How do I create an image with a
          servlet, for example, a graph out of a list of values?:
          
          http://java.apache.org/faq/fom-serve/cache/204.html
- WebCream - Java to HTML converter providing automatic
          conversion of Swing and AWT to HTML: http://creamtec.com:30422/webcream/
 
- Introduction to Java Course - Course Selections: 
      http://www.ibm.com/java/education/intro/courseoptions.htm
- Netscape JDK 1.1 Update Support: 
      http://developer.netscape.com/software/jdk/download.html
- How to make your older Netscape browser work with Java
      1.1. Less important now that Netscape 4.5 does.
- Java server performance (InfoWorld): 
      http://www.infoworld.com/cgi-bin/displayTC.pl?/980914analysis.htm#contents
- Performance comparison of servlet servers.
- IBM Aglets Workbench - Home Page: http://www.ibm.co.jp/trl/aglets/
- A proposed standard (with free supporting software) for
      mobile intelligent agents. Fascinating; worth study.
- Java Software: http://www-uk.hpl.hp.com/people/ak/java/
- The Kaffe Homepage: http://www.kaffe.org/
- GJ: Generic Java: http://www.cis.unisa.edu.au/~pizza/gj/
- EJBoss: http://www.ejboss.org/
- Ace's Hardware: 
      http://www.aceshardware.com/Spades/read.php?article_id=153
- Java Network Programming FAQ: 
      http://www.davidreilly.com/java/java_network_programming/
give me 
    feedback on this page // show previous 
    feedback on this page