//========================================================================
// LHW: Program: CheckName.java
//
// LHW: Author:  Francis Ng Hoong Kee 
// LHW: This is a sample program written for the UIT2201 Project
// LHW: The purpose of this program is to illustrate how to
// LHW: use a Java program to access an oracle database
// LHW: execute a query, and use the result
//
// LHW:   This program takes input a name
// LHW:      as the first parameter (which is args[0] below)
// LHW:   output: 1 if name is found, 2 if name is not found.
//
//

import java.sql.*;   // LHW: this imports sql related classes
import DBClasses.*;  // LHW: imports database manager and other classes


class CheckName {

  public static void main(String[] args) {

     // 1=found, 2=not found   (default is 2, not found)
     int found = 2;

     // LHW: Create a database connection
     // LHW:  by using the dbManager class provided  
     dbManager dbman = new dbManager();
     Connection conn = dbman.getConnection();

     try {
       // To execute query, 
       //   first create the sql statement
       //   execute the statement
       //   "catch" the output in "rs" (rs is a set of tuples)
       Statement stmt = conn.createStatement();
       String sql = "select username from names";      // prepare sql stmt
       ResultSet rs = stmt.executeQuery(sql);          // execute query

       while (rs.next()) {                             // process the result
         if (rs.getString(1).trim().equals(args[0])) {
           found=1;
           break;
         }
       }

       rs.close();       // close everything (rs, stmt, conn)
       stmt.close();
       conn.close();
    } catch (Exception e) {
      System.out.println("DB Error!"); // error message if exception occurs
      e.printStackTrace();
    }
     System.out.println(found);        // output the result;
  }
}
