Rev. Fr. Francis Thamburaj, SJ

Joy of Writing

WTeaching





Java Duke Ani 02

Java Data Base Connectivity

There are following six steps involved in building a JDBC application:

  1. Import the packages . Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
  2. Register the JDBC driver . Requires that you initialize a driver so you can open a communications channel with the database.
  3. Open a connection . Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
  4. Execute a query . Requires using an object of type Statement for building and submitting an SQL statement to the database.
  5. Extract data from result set . Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
  6. Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM’s garbage collection.

Program

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL

   //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   //static final String DB_URL = "jdbc:mysql://localhost/EMP";

   static final String JDBCDriver = “oracle.jdbc.driver.OracleDriver”;
   static final String DB_URL = " jdbc:oracle:
	thin:@192.168.1.1:1521:orcl";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection con = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName(JDBCDriver);

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      con = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = con.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      con.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)           stmt.close();
      }catch(SQLException se2){       }// nothing we can do
      try{
         if(conn!=null)           conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample




C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

All of you should write these in your note book without fail. I will check it in the next class. Those who have not written will be punished and marked absent.

Java Cup

Java Threads

Thread Synchronization

When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issue. For example if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overwrite data or while one thread is opening the same file at the same time another thread might be closing the same file.

So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block.

Program

class AC{
    private int balance=0;
    synchronized void credit(int amount){balance += amount;}
    void dispBalance(){System.out.println("Balance = "+balance);}
}
class ACH extends Thread{
    AC ac;
    ACH(AC ac){this.ac=ac;}
    public void run(){
        for(int j=0;j<10000;j++) ac.credit(10);
    }
}
public class ThreadSyncCredit {
    static int numACHolders=3;
    public static void main(String[] args){
        AC ac = new AC();
        ACH achs[] = new ACH[numACHolders];
        for(int k=0;k < numACHolders;k++){
            achs[k] = new ACH(ac);
            achs[k].start();
        }
        for(int i=0;i < numACHolders;i++){
            try{
                achs[i].join();
            }catch(Exception e){}
            ac.dispBalance();
        }
    }
}

All of you should write these in your note book without fail. I will check it in the next class. Those who have not written will be punished and marked absent.

Java Cup

Answers for Multiple Choice Questions

aaadacbba
Hiiiiiiiii ................. How is it?