Lab Session 4 - Building Database-Driven Applications

By Mitchell Welch

University of New England


Reading


Summary


Introduction


House Keeping


[mwelch8@turing ~]$ createdb -U mwelch8_apps -W -h 127.0.0.1 mwelch8_apps_prac_4
Password: 
[mwelch8@turing ~]$ psql -U mwelch8_apps -W -h 127.0.0.1 mwelch8_apps_prac_4
Password for user mwelch8_apps: 
psql (9.4.4)
Type "help" for help.

mwelch8_apps_prac_4=> \dt
No relations found.
mwelch8_apps_prac_4=> 

[mwelch8@turing ~]$ createdb mwelch8_prac_03
[mwelch8@turing ~]$ psql mwelch8_prac_03
psql (9.4.4)
Type "help" for help.

mwelch8_prac_03=> \i ~/prac_01.sql

...

mwelch8_prac_03=> \dt
             List of relations
 Schema |      Name      | Type  |  Owner  
--------+----------------+-------+---------
 public | department     | table | mwelch8
 public | dependent      | table | mwelch8
 public | dept_locations | table | mwelch8
 public | employee       | table | mwelch8
 public | project        | table | mwelch8
 public | works_on       | table | mwelch8
(6 rows)

Java Revision



/*************************************************************************
 *  Compilation:  javac HelloWorld.java
 *  Execution:    java HelloWorld
 *
 *  Prints "Hello, World". By tradition, this is everyone's first program.
 *
 *  % java HelloWorld
 *  Hello, World
 *
 *************************************************************************/

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}
21641:prac_4 mwelch8$ javac HelloWorld.java 
21641:prac_4 mwelch8$ ls
HelloWorld.class    HelloWorld.java     prac_4.md
21641:prac_4 mwelch8$ java HelloWorld
Hello, World
21641:prac_4 mwelch8$ 

import java.io.* ;


class InputExample {
     public static void main(String args[])
     {
          // Create a new InputStreamReader and connecting to STDIN 
          InputStreamReader istream = new InputStreamReader(System.in) ;

          // Create a new BufferedReader and connect it to the InputStreamReader
          // Now the plumbing is done, we can read from the BufferedReader
          BufferedReader bufRead = new BufferedReader(istream) ;

          /**********************************************************
          * The BufferedReader class a several methods for reading 
          * input:
          *  readLine() - reads a line of input from the stream
          *  read() -     returns the integer representation of the 
          *               next character in the stream.
          *  read(char[] cbuf,int off,int len)- 
          *               Reads len characters to the buf. 
          *
          **********************************************************/


          System.out.println("Welcome To My First Java Program");

          try {
               System.out.println("Please Enter In Your First Name: ");
               String firstName = bufRead.readLine();

               System.out.println("Please Enter In The Year You Were Born: ");
               String bornYear = bufRead.readLine();

               System.out.println("Please Enter In The Current Year: ");
               String thisYear = bufRead.readLine();

               int bYear = Integer.parseInt(bornYear);
               int tYear = Integer.parseInt(thisYear);

               int age = tYear-bYear;
               System.out.println("Hello " + firstName + " You are " 
                   + age + " years old");
          }
          catch (IOException err) {
               System.out.println("Error reading line");
          }
          catch(NumberFormatException err) {
               System.out.println(err);
          }         
     }
}

Connecting up JDBC

[comp389@turing prac_4]$ jar -xf postgresql-9.4-1201.jdbc4.jar 
[comp389@turing prac_4]$ ls
HelloWorld.java  META-INF  org  postgresql-9.4-1201.jdbc4.jar
[comp389@turing prac_4]$ 


import java.sql.*;
import java.util.*;

public class  DbTester{

    public static void main(String [] argv) throws Exception{

        Connection conn = null;
        try
        {

          Class.forName("org.postgresql.Driver");
          String url = "jdbc:postgresql://localhost/<une_username>_apps_prac_4";
          conn = DriverManager.getConnection(url,"<une_username>_apps", "<une_student_number>");

        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
          System.exit(1);
        }
        catch (SQLException e)
        {
          e.printStackTrace();
          System.exit(2);
        }
        //Now we're connected up lets retrieve a list of employees


        System.out.println("\n****Employees Currently Within the Database*****");
        System.out.println();
        //Print the column headings to the console
       System.out.printf("%-12s %-12s %n", "First Name","Last Name");
        System.out.println("--------------------");

        // First we specify our query
        String query = "SELECT fname, lname FROM employee;";
        Statement stmt = null;
        try {
        //Create an sql statement object
        stmt = conn.createStatement();
        //Execute the query
        ResultSet rs = stmt.executeQuery(query);
        //Iterate through the results and print to the console
        while (rs.next()) {
            String fName = rs.getString("fname");
            String lName = rs.getString("lname");
            System.out.printf("%-12s %-12s %n", fName,lName);
        }
        } catch (SQLException e ) {
        System.out.println(e);
        conn.close();
        System.exit(1);
        } 
        System.out.println("--------------------");
        System.out.println("\nQuery Executed Successfully...exiting");
        //Close the database connection
        conn.close();
      }

}


String url = "jdbc:postgresql://localhost/<une_username>_apps_prac_4";
conn = DriverManager.getConnection(url,"<une_username>_apps", "<une_student_number>");

[mwelch8@turing prac_4]$ javac DbTester.java 
[mwelch8@turing prac_4]$ java DbTester 

****Employees Currently Within the Database*****

First Name   Last Name    
--------------------
Alex         Freed        
Bob          Bender       
Evan         Wallis       
James        Borg         
Jared        James        
John         James        
Kim          Grace        
Ahmad        Jabbar       
Alicia       Zelaya       
Franklin     Wong         
Jennifer     Wallace      
Red          Bacher       
Sammy        Hall         
Carl         Reedy        
Naveen       Drew         
Ray          King         
Billie       King         
Jon          Kramer       
Arnold       Head         
Gerald       Small        
Helga        Pataki       
Lyle         Leslie       
Jill         Jarvis       
Kate         King         
Nandita      Ball         
Alec         Best         
Bonnie       Bays         
Sam          Snedden      
John         Smith        
Joyce        English      
Ramesh       Narayan      
Jeff         Chase        
Chris        Carter       
Jenny        Vos          
Andy         Vile         
Josh         Zell         
Tom          Brand        
Brad         Knight       
Jon          Jones        
Justin       Mark         
--------------------

Query Executed Successfully...exiting
[mwelch8@turing prac_4]$ 
Connection conn = null;
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost/<une_username>_apps_prac_4";
conn = DriverManager.getConnection(url,"<une_username>_apps", 

// First we specify our query
String query = "SELECT fname, lname FROM employee;";

stmt = conn.createStatement();
//Execute the query
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
            String fName = rs.getString("fname");
            String lName = rs.getString("lname");
            System.out.printf("%-12s %-12s %n", fName,lName);
        }

Exercises for You

  1. Modify the DbTester program so that it displayes the fname, lname, dbdate, sex and salary from the employee table in a formatted list with columns that are 12 characters wide with appropriate column headings.
  2. Modify the DbTester program so that it displays the department name (dname)and department location (dlocation) in addition to the attributes displayed in question 1.

Using JDBC to Create Records



import java.sql.*;
import java.util.*;

public class  DbInsert{

    public static void main(String [] argv) throws Exception{

        Connection conn = null;
        try
        {
          Class.forName("org.postgresql.Driver");

            String url = "jdbc:postgresql://localhost/<une_username>_apps_prac_4";

          conn = DriverManager.getConnection(url,"<une_username>_apps", "<une_student_number>");
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
          System.exit(1);
        }
        catch (SQLException e)
        {
          e.printStackTrace();
          System.exit(2);
        }
        //Now we're connected up lets retrieve a list of employees


        System.out.println("\n****Inserting a New Employee*****");
        System.out.println();


        // First we specify our query
        Statement stmt = null;
        try {
            //Create a new statement object - notice the additional arguments for inserting
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            //Get all record in the employee table
            ResultSet uprs = stmt.executeQuery("SELECT * FROM employee");
            /* - Employee table. Here to show column list
                CREATE TABLE employee (
                    fname character varying(15) NOT NULL,
                    minit character varying(1),
                    lname character varying(15) NOT NULL,
                    ssn character(9) NOT NULL,
                    bdate date,
                    address character varying(50),
                    sex character(1),
                    salary numeric(10,2),
                    superssn character(9),
                    dno integer
                );

            */
            //Create a new row in the ResultSet object
            uprs.moveToInsertRow();
            //Add new employee's information to the new row of data
            uprs.updateString("fname", "New_fname");
            uprs.updateString("minit", "S");
            uprs.updateString("lname", "New_lname");
            uprs.updateString("ssn", "112233445");
            uprs.updateInt("dno", 5);
            //Insert the new row of data to the database
            uprs.insertRow();
            //Move the cursor back to the start of the ResultSet object
            uprs.beforeFirst();
        } catch (SQLException e ) {
        System.out.println(e);
        conn.close();
        System.exit(1);
        } 

        System.out.println("\nQuery Executed Successfully...exiting");
        //Close the database connection
        conn.close();
      }

}

mwelch8_apps_prac_4=> select fname,lname from employee;

...

 Jon       | Jones
 Justin    | Mark
 New_fname | New_lname
(41 rows)

mwelch8_apps_prac_4=> 

           //Create a new row in the ResultSet object
            uprs.moveToInsertRow();
            //Add new employee's information to the new row of data
            uprs.updateString("fname", "New_fname");
            uprs.updateString("minit", "S");
            uprs.updateString("lname", "New_lname");
            uprs.updateString("ssn", "112233445");
            uprs.updateInt("dno", 5);
            //Insert the new row of data to the database
            uprs.insertRow();

Exercises for You

  1. Update the following program to insert the employee information entered through the console session.
import java.io.* ;


class CreateEmployee {


  public static void main(String args[]){

    // Database connection stuff as per the examples

    Connection conn = null;
    try
    {
      Class.forName("org.postgresql.Driver");
      String url = "jdbc:postgresql://localhost/<une_username>_apps_prac_4";
      conn = DriverManager.getConnection(url,"<une_username>_apps", "<une_student_number>");
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
      System.exit(1);
    }
    catch (SQLException e)
    {
      e.printStackTrace();
      System.exit(2);
    }

    /* - Employee table. Here to show column list
    CREATE TABLE employee (
    fname character varying(15) NOT NULL,
    minit character varying(1),
    lname character varying(15) NOT NULL,
    ssn character(9) NOT NULL,
    bdate date,
    address character varying(50),
    sex character(1),
    salary numeric(10,2),
    superssn character(9),
    dno integer
    );

    */

    try {
      System.out.println("Please Enter the employee's First Name: ");
      String firstName = bufRead.readLine();

      System.out.println("Please Enter the employee's middle initial: ");
      String minit = bufRead.readLine();

      System.out.println("Please Enter the employee's Last Name: ");
      String lastName = bufRead.readLine();

      System.out.println("Please Enter the employee's Ssn: ");
      String ssn = bufRead.readLine();

      System.out.println("Please Enter the employee's Department Number: ");
      String dno = bufRead.readLine();

      int dno_int = Integer.parseInt(dno);

      /*

      Add the additional data fields here

      */


    }catch (IOException err) {
      System.out.println(err);
    }catch(NumberFormatException err) {
      System.out.println(err);
    }

    //Now lets insert a new row of data

    System.out.println("\n****Inserting a New Employee*****");
    System.out.println();


    // First we specify our query
    Statement stmt = null;
    try {
      //Create a new statement object - notice the additional arguments for inserting
      stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      //Get all record in the employee table
      ResultSet uprs = stmt.executeQuery("SELECT * FROM employee");

      //Create a new row in the ResultSet object
      uprs.moveToInsertRow();
      //Add new employee's information to the new row of data

      /**********************************************************/
      // This is where you will need to update the code to include
      // the data entered by the user.

      uprs.updateString("fname", ... );
      uprs.updateString("minit", ... );
      uprs.updateString("lname", ... );
      uprs.updateString("ssn", ... );
      uprs.updateInt("dno", ... );
      /**********************************************************/
      //Insert the new row of data to the database
      uprs.insertRow();
      //Move the cursor back to the start of the ResultSet object
      uprs.beforeFirst();
    }catch (SQLException e ) {
      System.out.println(e);
      conn.close();
      System.exit(1);
    }

    System.out.println("\nQuery Executed Successfully...exiting");
    //Close the database connection
    conn.close();

  }


}