You are on page 1of 153

Core Java

Core Java | JDBC | Muralidhar


1
Agenda

Today we will cover the following three modules:

 Threads

 JDBC

2 Core Java | JDBC | Muralidhar


Day 5: Objectives

At the end of Day, you should be able to:


 Find more information about Threads
 Explain and define JDBC

3 Core Java | JDBC | Muralidhar


Core Java

Threads

Core Java | JDBC | Muralidhar


4
Module : objectives

After completion of this module, you should be able to:


 Define Threads
 Differentiate between Process and Thread
 Explain types of Thread
 Understand the life cycle of a thread
 Explain java thread states and how to use it in Java
 Create threads
 Identify the thread priorities
 Understand thread synchronization and inter-threaded communication
 Explain garbage collection

5 Core Java | JDBC | Muralidhar


Why threads?

 Improved performance
 Minimized system resource usage
 Simultaneous access to multiple applications
 Program structure simplification
 Send & receive data on network
 Read & write files to disk
 Perform useful computation (editor, browser, game)

6 Core Java | JDBC | Muralidhar


Precess vs thread

Process V S Thread

Definition

1. Executable program loaded in memory. 1. Sequentially executed stream of


instructions.

Address Space

2. Has own address space – variables & 2. Shares address space with other
data structures (in memory) threads.

7 Core Java | JDBC | Muralidhar


Precess vs thread

Process V S Thread

4. Communicate via operating system, files,


network. 4. Has own execution context.

5. May contain multiple threads.


5. Multiple thread in process execute same program.

8 Core Java | JDBC | Muralidhar


Types of thread

1. Single Threaded Process

2. Multi Threaded Process


Types of Thread

9 Core Java | JDBC | Muralidhar


Types of thread (continued)

1. Single Threaded Process

• A thread is defined as the execution of a program.


• A process that is made of one thread is known as single-threaded
process.

Single Thread

10 Core Java | JDBC | Muralidhar


Types of thread (continued)

2. Multi Threaded Process

• A process that creates two or more threads is called a


multithreaded process.

Two Threads

11 Core Java | JDBC | Muralidhar


Example: Thread

12 Core Java | JDBC | Muralidhar


Example: Thread (continued)

Web Server Multiple simultaneous


uses threads to handle web browser requests

13 Core Java | JDBC | Muralidhar


Basic concepts of multitasking

 Multitasking is the ability to execute more than one task at the


same time.
 Multitasking can be divided into two categories:

1. Process-based multitasking

2. Thread-based multitasking

14 Core Java | JDBC | Muralidhar


Basic concepts of multitasking (continued)

1. Process-based multitasking

 Refers to working with two programs concurrently.

 For example, working with MS-Word, Listening to mp3 song


using Windows Media Player.

15 Core Java | JDBC | Muralidhar


Basic concepts of multitasking (continued)

2. Thread-based multitasking

 Refers to working with parts of one program.

 For example, MS-Word program can check spelling, count line


numbers, column number while writing in a document.

16 Core Java | JDBC | Muralidhar


Disadvantage of multitasking

 Race condition
 Deadlock condition
 Lock starvation

17 Core Java | JDBC | Muralidhar


Using threads in Java

How To
Use
Threads in
Java
Using Thread
class

java.lang.Thread class is used to construct and access individuals


thread in a multi threaded application.

18 Core Java | JDBC | Muralidhar


Using threads in Java (continued)

Thread Class
Declaration

public class Thread extends Object


implements Runnable {
public Thread();
public Thread(String name); // Thread name
public Thread(Runnable r); // Thread  r.run()
public Thread(Runnable r, String name);

public void run();


public void start();// begin thread execution
...
}

19 Core Java | JDBC | Muralidhar


Using threads in Java (continued)

Thread Class
Methods

1. public void start() Starts a thread by calling the run() method.

2. public final String getName() Shows the name of the thread.

3. public static Thread currentThread() Returns a reference to the currently executing


thread object.

4. public void run() The entry point into thread.

20 Core Java | JDBC | Muralidhar


Using threads in Java (continued)

Thread Class
Methods

Determines whether a thread is running.


5. public final boolean isAlive()

Makes the thread to pause for a period of time in


6. public static void sleep(long millis) milliseconds.

7. public final void join()


Pauses until the thread terminates.

8. public static void yield()


Pauses the currently executing thread & allow
other to execute.

21 Core Java | JDBC | Muralidhar


Lifecycle of thread

Refers to current class object

New Created by instantiating the Thread class.

Thread th=new Thread (this);

Runnable By calling the start() method that in turn call run() method.

th.start();

Not Runnable Calling wait() or sleep() method or caused due to IO interrupts.


th.wait();
th.sleep(1000);
Dead or Terminate After the run() method completes execution.

public void run { …… }


22 Core Java | JDBC | Muralidhar
Lifecycle of thread (continued)

New Thread created Suspended


st
ar
t( ) notify()
ca wait()
l
s l
run
()

sleep() stop()
Sleeping Running Terminated
timeout return

23 Core Java | JDBC | Muralidhar


Java thread states

Java thread can be in one of these states

New Thread allocated & waiting for start.

Runnable Thread can begin execution.

Running Thread currently executing.

Blocked Thread waiting for event (I/O, etc.)

Dead Thread finished execution.

24 Core Java | JDBC | Muralidhar


Java thread states (continued)

State Diagram

new start
notify, notifyAll,
new runnable
IO complete,
sleep expired,
scheduler yield, join complete
time slice

running blocked
IO, sleep,
terminate wait, join

dead

25 Core Java | JDBC | Muralidhar


Creating threads

• Two ways of creating Thread in Java:


1. Extending from java.lang.Thread class
2. Implementing the Runnable Interface

26 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

• The class extending the Thread class calls start() method to begin
executing child thread.
Sample
Code
public class MyT extends Thread {
public void run() {

}
}
MyT T = new MyT () ; // create thread
T.start(); // begin running thread

27 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

class MyThread extends Thread {


private String name, msg; Code to create
Thread using
for (int i = 0; i < =5; i++) {
Thread class
public MyThread(String name, String msg) { System.out.println(name + " says: "
this.name = name; + msg+” for “+i+” time/s”);
try {
this.msg = msg; Thread.sleep(2000);
} }
catch (InterruptedException ie) {}
}// End of For Loop
public void run() { System.out.println(name + " finished
execution");
System.out.println(name + " starts its
}
execution");
}
28 Core Java | JDBC | Muralidhar
Creating threads (continued)

1. Extending from java.lang.Thread class

class MyThread extends Thread { for (int i = 0; i < =5; i++) {


private String name, msg; System.out.println(name + " says: "
+ msg+” for “+i+” time/s”);
try {
public MyThread(String name, String msg) { Thread.sleep(2000);
this.name = name; }
catch (InterruptedException ie) {}
this.msg = msg;
}// End of For Loop
} System.out.println(name + " finished
execution");
}
public void run() { }
System.out.println(name + " starts its
execution");

29 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

class MyThread extends Thread { for (int i = 1; i < =5; i++) {


private String name, msg; System.out.println(name + " says: "
+ msg+” for “+i+” time/s”);
try {
public MyThread(String name, String msg) { Thread.sleep(2000);
this.name = name; }
catch (InterruptedException ie) {}
this.msg = msg;
Overridde }// End of For Loop
} System.out.println(name + " finished
n Method
execution");
}
public void run() { }
System.out.println(name + " starts its
execution");

30 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

class MyThread extends Thread { for (int i = 1; i < =5; i++) {


private String name, msg; System.out.println(name + " says: "
+ msg+” for “+i+” time/s”);
try {
public MyThread(String name, String msg) { Thread.sleep(2000);
this.name = name; }
catch (InterruptedException ie) {}
this.msg = msg;
It will throw an }// End of For Loop
} InterruptedException System.out.println(name + " finished
execution");
}
public void run() { }
System.out.println(name + " starts its
execution");

31 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

class MyThread extends Thread { for (int i = 1; i < =5; i++) {


private String name, msg; System.out.println(name + " says: "
+ msg+” for “+i+” time/s”);
try {
public MyThread(String name, String msg) { Thread.sleep(2000);
this.name = name; }
catch (InterruptedException ie) {}
this.msg = msg;
}// End of For Loop
} Caught by
System.out.println(name + " finished
execution");
}
public void run() { }
System.out.println(name + " starts its
execution");

32 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

How to Use Our


Thread that we
have created

33 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

public class TestMyThread


{
public static void main(String[] args)
{
MyThread mth1 = new MyThread(“IBM", “Hello");
mth1.start();
}
}

34 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

public class TestMyThread


{
A New
public static void main(String[] args) Thread
{ Created But
MyThread mth1 = new MyThread(“IBM", “Hello");
Not
Running
mth1.start();
}
}

35 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

run() method
public class TestMyThread
is called.
{ The New
public static void main(String[] args) Thread
moves to
{
runnable
MyThread mth1 = new MyThread(“IBM", “Hello"); state or to
mth1.start(); the running
state
} depending
} upon the
scheduler.
36 Core Java | JDBC | Muralidhar
Creating threads (continued)

1. Extending from java.lang.Thread class

Can U Predict The


Output of the
Program

37 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

38 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

39 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

40 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

41 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

42 Core Java | JDBC | Muralidhar


Creating threads (continued)

1. Extending from java.lang.Thread class

43 Core Java | JDBC | Muralidhar


Creating threads (continued)

2. Implementing the Runnable Interface

• The Runnable interface only consists of run() method.


• When a program needs to be inherited from a class other than Thread
class, you need to implement the Runnable interface.
Sample
Code
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread T = new Thread(new MyT()); // create thread
T.start(); // begin running thread

44 Core Java | JDBC | Muralidhar


Creating threads (continued)

2. Implementing the Runnable Interface

class MyRunnable implements Runnable { for (int i = 1; i < =5; i++) {


Code to create
private String name, msg; System.out.println(name + " says: "
Thread using
+ msg+” for “+i+” time/s”);
Runnable
try {
Interface
public MyRunnable(String name, String msg) { Thread.sleep(2000);
this.name = name; }
catch (InterruptedException ie) {}
this.msg = msg;
}// End of For Loop
} System.out.println(name + " finished
execution");
}
public void run() { }
System.out.println(name + " starts its
execution");

45 Core Java | JDBC | Muralidhar


Creating threads (continued)

2. Implementing the Runnable Interface

class MyRunnable implements Runnable { for (int i = 1; i < =5; i++) {


private String name, msg; System.out.println(name + " says: "
+ msg+” for “+i+” time/s”);
try {
public MyRunnable(String name, String msg) { Thread.sleep(2000);
this.name = name; }
catch (InterruptedException ie) {}
this.msg = msg;
}// End of For Loop
} System.out.println(name + " finished
execution");
}
public void run() { }
System.out.println(name + " starts its
execution");
46 Core Java | JDBC | Muralidhar
Creating threads (continued)

2. Implementing the Runnable Interface

class MyRunnable implements Runnable { for (int i = 1; i < =5; i++) {


private String name, msg; System.out.println(name + " says: "
+ msg+” for “+i+” time/s”);
try {
public MyRunnable(String name, String msg) { Thread.sleep(2000);
this.name = name; }
Defining the catch (InterruptedException ie) {}
this.msg = msg; behavior of run }// End of For Loop
} method declared System.out.println(name + " finished
in the Runnable execution");
interface }
public void run() { }
System.out.println(name + " starts its
execution");

47 Core Java | JDBC | Muralidhar


Creating threads (continued)

2. Implementing the Runnable Interface

public class TestMyRunnable


{
public static void main(String[] args)
{
MyRunnable myrun = new MyRunnable(“IBM", “Hello");
Thread mythread = new Thread(myrun);
mythread.start();
}
}

48 Core Java | JDBC | Muralidhar


Creating threads (continued)

2. Implementing the Runnable Interface

public class TestMyRunnable A New


Runnable
{
object is
public static void main(String[] args) created
{
MyRunnable myrun = new MyRunnable(“IBM", “Hello");
Thread mythread = new Thread(myrun);
mythread.start();
}
}
49 Core Java | JDBC | Muralidhar
Creating threads (continued)

2. Implementing the Runnable Interface

public class TestMyRunnable A New


Thread is
{
created
public static void main(String[] args)
{
MyRunnable myrun = new MyRunnable(“IBM", “Hello");
Thread mythread = new Thread(myrun);
mythread.start();
}
}
50 Core Java | JDBC | Muralidhar
Creating threads (continued)

2. Implementing the Runnable Interface

A newly
public class TestMyRunnable created
{ thread is
moved either
public static void main(String[] args) to runnable
{ or running
state by the
MyRunnable myrun = new MyRunnable(“IBM", “Hello"); scheduler
Thread mythread = new Thread(myrun);
mythread.start();
}
}
51 Core Java | JDBC | Muralidhar
Creating threads (continued)

2. Implementing the Runnable Interface

Same Output As In The


Case Of
TestMyThread class

52 Core Java | JDBC | Muralidhar


Java multi threading example (continued)
Sample
Code
public class MultiThreadExample extends Thread {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
try {
sleep((int)(Math.random() * 5000)); // sleep for 5 seconds.
} catch (InterruptedException e) { }
}
public static void main(String[] args) {
new MultiThreadExample().start();
new MultiThreadExample().start();
System.out.println("Done");
}
}

53 Core Java | JDBC | Muralidhar


Java multi threading example (continued)

Possible
Outputs

0, 1, 2, 0, 1, 2, Done // thread1, thread2, main()


0, 1, 2, Done, 0, 1, 2 // thread1, main(), thread2
Done, 0, 1, 2, 0, 1, 2 // main(), thread1, thread2
0, 0, 1, 1, 2, Done, 2 // main() & threads interleaved

54 Core Java | JDBC | Muralidhar


Using threads in Java

Point To Be Noted

The first thread to be executed in a multithreaded


process is called the main thread.
The main thread is created automatically on the
startup of java program execution.

55 Core Java | JDBC | Muralidhar


Threads scheduling

Scheduling The execution of multiple threads on a single CPU is called


scheduling.

 Determines which runnable threads to run


 Can be based on thread priority
 Part of OS or Java Virtual Machine (JVM)

The Java runtime supports a very simple, deterministic scheduling


algorithm known as fixed priority scheduling.

56 Core Java | JDBC | Muralidhar


Thread policy

 Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
 Each Java thread is given a numeric priority between MIN_PRIORITY and
MAX_PRIORITY.
 The Java Run-time system selects the runnable thread with the highest
priority of execution when a number of threads get ready to execute.
 The Java Run-time Environment executes threads based on their priority.
 A thread with higher priority runs before threads with low priority.
 A given thread may, at any time, give up its right to execute by calling the
yield method. Threads can only yield the CPU to other threads of the
same priority--attempts to yield to a lower priority thread are ignored.

57 Core Java | JDBC | Muralidhar


Thread policy (continued)

Setting Thread Priority

• You can set the thread priority after it is created using the setPriority() method declared in the Thread class.

Syntax for
setPriority
method

public final void setPriority (int newPriority)

58 Core Java | JDBC | Muralidhar


Thread synchronization

Why Synchronization?

Problem:
Race condition!
 Two or more threads access to same object and each call a method that modifies the
state of the object.

Result:
Corrupted
object

59 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

What is the Solution?

Synchronization

60 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

Unsynchronized Synchronized
Thread 1 Thread 2 Thread 1 Thread 2

Time
Transfer

Transfer Transfer

Transfer

61 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

What is Synchronization?

Synchronization of threads ensures that if two or more threads need to access


a shared resource then that resource is used by only one thread at a time.

• Synchronization is based on the concept of monitor.

What is a Monitor?
A monitor is an object that can block threads and notify them when it is available.

• The monitor controls the way in which synchronized methods access an object or class.
• To enter an object’s monitor, you need to call a synchronized method.

62 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

How To Achieve Synchronization?

Using

synchronized keyword

 Object Locks
63 Core Java | JDBC | Muralidhar
Thread synchronization (continued)

Synchronization can be achieved at


two levels

1. Method Level

2. Object Level

64 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

1. Synchronizing A Method

public synchronized void updateRecord()


{
// critical code goes here …
}

65 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

1. Synchronizing A Method

public synchronized void updateRecord()


{
// critical code goes here …
} Only one thread will be inside the body of the
updateRecord() method. The second call will be
blocked until the first call returns or wait() is called
inside the synchronized method.

66 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

2. Synchronizing An Object
public void updateRecord()
{
synchronized (this)
{
// critical code goes here …
}
}

67 Core Java | JDBC | Muralidhar


Thread synchronization (continued)

2. Synchronizing An Object
public void updateRecord()
{
synchronized (this)
{
// critical code goes here …
}
}

68 Core Java | JDBC | Muralidhar


Interthread communication

What is Interthread communication?

A thread may notify another thread that the task has been completed. This
communication between threads is known as interthread communication.

• The various methods used in interthread communication


are:
 wait()
 notify()
 notifyAll()

69 Core Java | JDBC | Muralidhar


Garbage collection

Garbage collection is the feature of Java that helps to automatically destroy the
objects created and release their memory for future reallocation.

• The various activities involved in garbage collection are:


 Monitoring the objects used by a program and
determining when they are not in use.
 Destroying objects that are no more in use and reclaiming
their resources, such as memory space.
 The Java Virtual machine (JVM) acts as the garbage
collector that keeps a track of the memory allocated to
various objects and the objects being referenced.
Java use a thread to do
garbage collection in the background
70 Core Java | JDBC | Muralidhar
Exercise
 Write a program that will display even number every after
1.5 seconds and a odd number every after 3 seconds and
ensure that the main thread is the last thread to finish?
Note: For First 20 Natural Numbers.
The program should look like this?

71 Core Java | JDBC | Muralidhar


Summary

 A thread is defined as the path of execution of a program. It is a


sequence of instructions that is executed to define a unique flow of
control.
 A program that creates two or more threads is called a multithreaded
program.
 The two types of multitasking are:
– Process-based
– Thread-based
• The various advantages of multithreading are:
– Improved Performance
– Minimized System Resources Usage
–Simultaneous access to multiple applications

72 Core Java | JDBC | Muralidhar


Summary (continued)

 The various disadvantages of multithreading are:


– Race condition
– Deadlock
– Lock starvation
 The java.lang.Thread class is used to construct and access individual
threads in a multithreaded application.
 The various states in the life cycle of a thread are:
– New
– Runnable
– Not Runnable
–Terminated or Dead
 You can create a thread in the following ways:
–Extending the Thread class
–Implementing Runnable interface
73 Core Java | JDBC | Muralidhar
Summary (continued)

 Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
 You can set the thread priority after it is created using the setPriority()
method declared in the Thread class.
 Synchronization of threads ensures that if two or more threads need to
access a shared resource, the resource is used by only one thread at a
time.
 Various threads can communicate with each other using the following
methods:
– wait()
– notify()
– notifyAll()
 Garbage collection is the feature of Java that helps to automatically
destroy the objects created and release their memory for future
reallocation.
74 Core Java | JDBC | Muralidhar
Summary (continued)

 Sun offers an easy-to-use package for handling XML data in Java.


 In XML we work more with hierarchy.
 Java API for XML processing (JAXP) lets you access XML documents either
serially (SAX) or in random access mode (DOM).
 DOM:
– A tree-based API (such as DOM) builds an in-memory tree representation
of the XML document.
 SAX :
– An event-based API, uses calls to report parsing events to the
application.

75 Core Java | JDBC | Muralidhar


References

 http://www.devarticles.com/c/a/Java/Multithreading-in-Java
 http://java.sun.com/docs/books/tutorial
 http://java.sun.com/j2se/1.3/docs/api/java/lang/Runnable.html
 http://telecom.ntua.gr/HTML.Tutorials/applet/overview/threads.html
 http://java.sun.com/docs/books/tutorial/essential/threads/

76 Core Java | JDBC | Muralidhar


Core Java

JDBC

Core Java | JDBC | Muralidhar


77
Objectives

After completion of this module, you should be able to:


 Define database and their architecture
 Define JDBC architecture
 Explain JDBC drivers
 Explain JDBC API
 Explain transaction

78 Core Java | JDBC | Muralidhar


Database architecture

 There are three types of database architecture, such as:


 Two-tier
 Three-tier
 N-tier

79 Core Java | JDBC | Muralidhar


Two-tier architecture

 Client connects directly to server


e.g. HTTP, email.

80 Core Java | JDBC | Muralidhar


Two-tier pros

 Simple.
 Client-side scripting offloads work
onto the client.

81 Core Java | JDBC | Muralidhar


Two-tier cons

User Interface
 Fat client
 Server bottlenecks Client Layer UI Logic
 Software Distribution
problem Business Logic
 Inflexible

Network
User Data
DML Operations
Validation
Checks

Server Layer Database


Tables
82 Core Java | JDBC | Muralidhar
Three-Tier Architecture

User Interface
 Application Server sits between
client and database. Client Layer
UI Logic

Network
Business Messages

Application Server Business Logic


Layer

Network
User Data
DML
Operations
Validation
Checks
Database Server Database
Layer Tables

83 Core Java | JDBC | Muralidhar


Three-tier pros

 flexible: can change one part


without affecting others
 can connect to different databases
without changing code
 specialization: presentation /
business logic / data management
 can cache queries

84 Core Java | JDBC | Muralidhar


Three-tier cons

 higher complexity
 higher maintenance
 lower network efficiency
 more parts to configure (and buy)

85 Core Java | JDBC | Muralidhar


N-tier architecture

 Design your application using as many “tiers” as you need


 Use Object-Oriented Design techniques
 Put the various components on whatever host makes sense
 Java allows N-Tier Architecture, especially with RMI and JDBC

86 Core Java | JDBC | Muralidhar


Java application connects to database

Java Application Connects to Database


 The below given figure shows the Employee Logging System
application developed in Java interacting with the Employee database
using the JDBC API:

Employee Logging System


RDBMS
EmpName
EmployeeLog
E-Mail Address JDBC API Name Email

Submit Clear

87 Core Java | JDBC | Muralidhar


JDBC architecture
• It can be categorized into into two layers:

JDBC Application Layer JDBC Driver Layer

Driver Oracle

Java JDBC
Driver DB2
Application API

Driver SQL Server

88 Core Java | JDBC | Muralidhar


JDBC architecture (continued)

Application JDBC Driver

 Java code calls JDBC library


 JDBC loads a driver
 Driver talks to a particular database
 Can have more than one driver -> more than one database
 Can change database engines without changing any application code

89 Core Java | JDBC | Muralidhar


JDBC drivers

 Type I: “Bridge” - JDBC-ODBC Bridge Driver

 Type II: “Native” -


Native-API Partly-Java Driver

 Type III: “Middleware” -


JDBC-Net Pure-Java Driver

 Type IV: “Pure” -


Native Protocol Pure-Java Driver

Overview of All Drivers

90 Core Java | JDBC | Muralidhar


Type 1 drivers

 Use bridging technology

 Translates query obtained by


JDBC into corresponding ODBC
query, which is then handled by
the ODBC driver.

 Almost any database for which


ODBC driver is installed, can be
accessed.

Go Back To
JDBC Driver List

91 Core Java | JDBC | Muralidhar


Disadvantage of Type-I Driver

 Performance overhead since the calls have to go through the JDBC


overhead bridge to the ODBC driver, then to the native db
connectivity interface.

 The ODBC driver needs to be installed on the client machine.

 Not good for Web

Go Back To
JDBC Driver List

92 Core Java | JDBC | Muralidhar


Type II drivers

 Native API drivers

 Better performance than Type 1


since no jdbc to odbc translation is
needed.

 Converts JDBC calls into calls to


the client API for that database.

Go Back To
JDBC Driver List

93 Core Java | JDBC | Muralidhar


Disadvantage of Type-II Driver

 The vendor client library needs to be installed on the client machine.


 Cannot be used in internet due the client side software needed.
 The driver is compiled for use with the particular operating system.
 Mostly obsolete now
 Not good for Web

Go Back To
JDBC Driver List

94 Core Java | JDBC | Muralidhar


Type III drivers

 Follows a three tier communication


approach.

 Calls middleware server, usually on


database host

 Very flexible -- allows access to


multiple databases using one driver

 Only need to download one driver

Go Back To
JDBC Driver List

95 Core Java | JDBC | Muralidhar


Disadvantage of Type-III Driver

 Requires database-specific coding to be done in the middle tier.

 An extra layer added may result in a time-bottleneck.

Go Back To
JDBC Driver List

96 Core Java | JDBC | Muralidhar


Type IV drivers

 100% Pure Java -- the Holy Grail


 Communicate directly with a vendor’s
database through socket connection
 Use Java networking libraries to talk
directly to database engines
 e.g include the widely used Oracle
thin driver - oracle.jdbc.driver.
OracleDriver

Go Back To
JDBC Driver List

97 Core Java | JDBC | Muralidhar


Disadvantage of Type-IV Driver

 At client side, a separate driver is needed for each database

Go Back To
JDBC Driver List

98 Core Java | JDBC | Muralidhar


JDBC drivers (figure)

Type I ODBC
JDBC
“Bridge” Driver

Type II
“Native” CLI (.lib)

JDBC
Type III Middleware
“Middleware” Server

Type IV
“Pure”
99 Core Java | JDBC | Muralidhar
Related technoligies

 ODBC
– Requires configuration (odbc.ini)
 RDO, ADO
– Requires Win32
 JavaBlend
– maps objects to tables transparently (more or less)

100 Core Java | JDBC | Muralidhar


Core Java

JDBC API

Core Java | JDBC | Muralidhar


101
JDBC API

 The JDBC API classes and interfaces are available in the java.sql and the
javax.sql packages.
 The commonly used classes and interfaces in the JDBC API are:
– DriverManager class: Loads the driver for a database.
– Driver interface: Represents a database driver. All JDBC driver classes must
implement the Driver interface.
– Connection interface: Enables you to establish a connection between a Java
application and a database.

102 Core Java | JDBC | Muralidhar


JDBC API (continued)

 Statement interface: Enables you to execute SQL statements.


 ResultSet interface: Represents the information retrieved from a
database.
 SQLException class: Provides information about the exceptions that
occur while interacting with databases.

103 Core Java | JDBC | Muralidhar


Steps to create JDBC application

DriverManager

Driver

Connection

Statement

ResultSet

104 Core Java | JDBC | Muralidhar


Steps to create JDBC application (continued)

Load A Driver

Connect to a Database

Create and execute SQL statements

Handle SQL Exception

105 Core Java | JDBC | Muralidhar


JDBC API (continued)

Load A Driver

 Loading a Driver can be done in two ways:


 Programmatically:
– Using the forName() method
– Using the registerDriver()method
 Manually:
– By setting system property

106 Core Java | JDBC | Muralidhar


JDBC API (continued)

Load A Driver (Programmatically)

 Using the forName() method

– The forName() method is available in the java.lang.Class class.


– The forName() method loads the JDBC driver and registers the driver with the
driver manager.
– The method call to use the the forName() method is:
– Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

107 Core Java | JDBC | Muralidhar


JDBC API (continued)

Load A Driver (Programmatically)

 Using the registerDriver() method


– You can create an instance of the Driver class to load a JDBC driver.
– This instance provide the name of the driver class at run time.
– The statement to create an instance of the Driver class is:
– Driver d = new
sun.jdbc.odbc.JdbcOdbcDriver();
– You need to call the registerDriver() method to register the Driver object with the
DriverManager.
– The method call to register the JDBC-ODBC Bridge driver is:
– DriverManager.registerDriver(d);

108 Core Java | JDBC | Muralidhar


JDBC API (continued)

Connect to a Database

 Connecting to a Database Using DriverManager.getConnection() method:


– Connection getConnection (String <url>)
– Connection getConnection (String <url>, String <username>, String <password>)
• Connects to given JDBC URL.
• throws java.sql.SQLException
• Returns a connection object.

Example:
Connection
con=DriverManager.getConnection(“jdbc:odbc:MyDSN”,”scott”,”tiger
”);

109 Core Java | JDBC | Muralidhar


JDBC API (continued)

Connect to a Database (Example)


String url = "jdbc:odbc:Northwind";
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }

110 Core Java | JDBC | Muralidhar


JDBC API (continued)

Create and Execute SQL Statements


 Statement Interface
– A Statement object is used for executing a static SQL statement and
obtaining the results produced by it.
Statement createStatement()
– returns a new Statement object.
 Prepared Statement Interface
When you use a PreparedStatement object to execute a SQL statement, the
statement is parsed and compiled by the database, and then placed in a
statement cache. From then on, each time you execute the same
PreparedStatement, it is once again parsed, but no recompile occurs. Instead,
the precompiled statement is found in the cache and is reused.
PreparedStatement prepareStatement(String sql)
– returns a new PreparedStatement object.

111 Core Java | JDBC | Muralidhar


JDBC API (continued)
Create and Execute SQL Statements
 CallableStatement Interface
– The interface used to execute SQL stored procedures.
– Syntax:
 CallableStatement cl = con.prepareCall(“{call show_emp}”);
- Where, con is the connection identifier and show_emp is the procedure name.

112 Core Java | JDBC | Muralidhar


JDBC API (continued)

Statement Interface Methods


 ResultSet executeQuery(String)
– Execute a SQL statement that returns a single ResultSet.
 int executeUpdate(String)
– Execute a SQL INSERT, UPDATE or DELETE statement.
Returns the number of rows changed.
 boolean execute(String)
– Execute a SQL statement that may return multiple results.

113 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Interface

 A ResultSet provides access to a table of data generated by


executing a Statement.
 Only one ResultSet per Statement can be open at once.
 The table rows are retrieved in sequence.
 A ResultSet maintains a cursor pointing to its current row of data.
 The 'next' method moves the cursor to the next row.
– you can’t rewind

114 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods

 boolean next()
– activates the next row
– the first call to next() activates the first row
– returns false if there are no more rows
 void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it

115 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

 Type getType(int columnIndex)


– returns the given field as the given type
– fields indexed starting at 1 (not 0)
 Type getType(String columnName)
– same, but uses name of field
– less efficient
 int findColumn(String columnName)
– looks up column index given column name

116 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

 String getString(int columnIndex) • float getFloat(int columnIndex)



• double getDouble(int columnIndex)
boolean getBoolean(int columnIndex)
• Date getDate(int columnIndex)
 Explore ResultSet MethodsTime getTime(int columnIndex)
byte getByte(int columnIndex) •
 short getShort(int columnIndex) • Timestamp getTimestamp(int
columnIndex)
 int getInt(int columnIndex)
 long getLong(int columnIndex)

117 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

Method Name Description


1. boolean first() 1. Shifts the control of a result set
cursor to the first row of the result
set.
2. boolean isFirst()
2. checks whether result set cursor
points to the first row or not.

3. boolean beforeFirst() 3. moves the cursor before the first


row.
4. boolean isbeforeFirst() 4. Checks whether result set cursor
moves before the first row.

118 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

Method Name Description


5. boolean last() 5. Shifts the control to the last row of
result set cursor.
6. boolean isLast()
6. checks whether result set cursor
points to the last row or not.

7. boolean afterLast() 7. moves the cursor after the last


row.
8. boolean isAfterLast() 8. Checks whether result set cursor
moves after the last row.

119 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

Method Name Description


9. boolean next() 9. Shifts the control to the next row of
result set.
10. Shifts the control to the previous
10. boolean previous() row of the result set.

11. boolean absolute(int rowno) 11. Shifts the cursor to the row number
that you specify as an argument.

12. Shifts the cursor relative to the row


12. boolean relative(int rowno) number that you specify as an
argument.

120 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

Method Name Description


13. void insertRow() 13. Inserts a row in the current result
set.

14. void deleteRow() 14. Deletes a row in the current result


set.

15. void updateRow()


15. Updates a row of the current
resultset.

121 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Methods (Continued)

Method Name Description


16. void updateString(col name, String s) 16. Updates the specified column
name with the given string value.
17. void updateInt(col name, int x)
17. Updates the specified column
name with the given int value.

18. void updateFloat() 18. Updates the specified column


name with the given float value.
19. void cancelRowUpdates() 19. Cancels all of the updates in a row.

122 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Fields

Field Name Description


1. TYPE_FORWARD_ONLY 1. The ResultSet object can moves
forward only from first to last row.
2. TYPE_SCROLL_SENSITIVE
2. Indicates ResultSet is scrollable
and it reflects changes in the data
made by other user.

3. TYPE_SCROLL_INSENSITIVE 3. Indicates ResultSet is scrollable


and does not reflect changes in the
data made by other user.

123 Core Java | JDBC | Muralidhar


JDBC API (continued)

ResultSet Fields

Field Name Description


4. CONCUR_READ_ONLY 4. Does not allow to update the
ResultSet object.

5. CONCUR_UPDATABLE 5. Allows to update the ResultSet


object .

124 Core Java | JDBC | Muralidhar


JDBC API (continued)

SQL Syntax

INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 )


inserts a new record into the named table
UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE
condition
changes an existing record or records
DELETE FROM table WHERE condition
removes all records that match condition
SELECT field1, field2 FROM table WHERE condition
retrieves all records that match condition

125 Core Java | JDBC | Muralidhar


JDBC API (continued)

Database Operations

Querying a table

Inserting rows

Updating rows

Deleting rows

126 Core Java | JDBC | Muralidhar


JDBC API (continued)

Database Operations

Querying a table

The code snippet to retrieve data from


the employees table is:
String semp = "SELECT * FROM employees";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(semp);

127 Core Java | JDBC | Muralidhar


JDBC API (continued)

Database Operations

Inserting rows

The code snippet to insert rows in employees table is:

String semp = “INSERT INTO employees(eid, ename,


basic) VALUES(1,’A.Sinha’,28000)”;
Statement stmt = con.createStatement();
int noOfInsert = stmt.executeUpdate(semp);

128 Core Java | JDBC | Muralidhar


JDBC API (continued)

Database Operations

Updating rows

The code snippet to insert rows in employees table is:

String semp = “UPDATE employees SET


basic=basic+2000 where eid=1”;
Statement stmt = con.createStatement();
int noOfUpdate = stmt.executeUpdate(semp);

129 Core Java | JDBC | Muralidhar


JDBC API (continued)

Database Operations

Deleting rows

The code snippet to delete rows in employees table is:

String semp = “DELETE FROM employees WHERE


eid=1”;
Statement stmt = con.createStatement();
int noOfDelete = stmt.executeUpdate(semp);

130 Core Java | JDBC | Muralidhar


JDBC API (continued)

DDL Operations

Creating Table

Altering Table

Dropping Table

131 Core Java | JDBC | Muralidhar


JDBC API (continued)

DDL Operations

Creating Table

The code snippet to create a department table is:

Statement stmt = con.createStatement();


stmt.execute(“create table department(eid number(5),
deptno char(10), deptname varchar2(20)” );

132 Core Java | JDBC | Muralidhar


JDBC API (continued)

DDL Operations

Altering Table

The code snippet to add a column in department


table is:

Statement stmt = con.createStatement();


stmt.execute(“ALTER TABLE department add depthead
varchar2(15)”);

133 Core Java | JDBC | Muralidhar


JDBC API (continued)

DDL Operations

Dropping Table

The code snippet to create a department table is:

Statement stmt = con.createStatement();


stmt.execute(“DROP TABLE department” );

134 Core Java | JDBC | Muralidhar


JDBC API (continued)

PreparedStatement Interface
• The PreparedStatement Interface object:
 pass runtime parameters to the SQL statements.
 Is compiled and prepared only once by the
JDBC.
 prepareStatement() method is used to submit
parameterized query using a connection object to
the database.

135 Core Java | JDBC | Muralidhar


JDBC API (continued)

PreparedStatement Interface (Continued)

Code snippet for preparedStatement:


The code snippet to pass the employee id during
It acts as a
The value runtime using prepareStatement() method: placeholder
of each ‘?’
is set by String s=“select * from employee where eid=? “
calling PreparedStatement pst = con.prepareStatement(s);
appropriate
setXXX() pst.setInt(1,100 );
method, In ResultSet rs=pst.executeQuery();
this case
setInt()

136 Core Java | JDBC | Muralidhar


JDBC API (continued)

CallableStatement Interface
Code snippet for Creating show_emp Stored
Procedure:

String crProc=“create procedure show_emp as


select * from emp”;
Statement st = con.createStatement();
st.executeUpdate(crProc);

137 Core Java | JDBC | Muralidhar


JDBC API (continued)

CallableStatement Interface
Code snippet for Calling show_emp Stored
Procedure:

CallableStatement clst = con.prepareCall(“{call


show_emp}”);
ResultSet rs = clst.executeQuery();
// … Fetch the Data

138 Core Java | JDBC | Muralidhar


JDBC API (continued)

Mapping Java Types to SQL Types


SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp

139 Core Java | JDBC | Muralidhar


Transaction

Transactions Overview

 Transaction = more than one statement which must all succeed (or all
fail) together
 If one fails, the system must reverse all previous actions
 Also can’t leave DB in inconsistent state halfway through a transaction
 COMMIT = complete transaction
 ROLLBACK = abort

140 Core Java | JDBC | Muralidhar


Transaction (continued)

Transaction Management
 Transactions are not explicitly opened and closed
 if AutoCommit is true, then every statement is automatically committed
 default case: true
 if AutoCommit is false, then every statement is added to an ongoing
transaction
 Must explicitly rollback or commit.

141 Core Java | JDBC | Muralidhar


JDBC class diagram

142 Core Java | JDBC | Muralidhar


Exercise

 Create the following Menu as shown below:


********************************** Book Details **********************************
1. Create A Employee Table
2. Insert A New B Employee
3. Delete A Employee
4. Update A Employee
5. Retrieve Employee Details
6. Exit
*************************************************************************************

143 Core Java | JDBC | Muralidhar


Exercise (continued)

 Description of the Menu Option’s


1. Create A Book Table – The structure of the table is given below:
Field Name DataType
EMP_ID NUMBER(4)
EMP_NAME VARCHAR2(20)
AGE NUMBER(4)
DEPT NUMBER(4)

144 Core Java | JDBC | Muralidhar


Summary

 JDBC Architecture consists of two layers:


– JDBC application layer: Signifies a Java application that uses the JDBC API to
interact with the JDBC driver manager.
– JDBC driver layer: Contains a driver, such as an SQL Server driver, which
enables a Java application to connect to a database. This layer acts as an
interface between a Java application and a database.

 The JDBC driver manager manages various JDBC drivers.


 The JDBC driver is software that a Java application uses to access a
database.

145 Core Java | JDBC | Muralidhar


Summary (continued)

 JDBC supports four types of drivers:


– JDBC-ODBC Bridge driver.
– Native-API Partly-Java driver.
– JDBC-Net Pure-Java driver.
– Native Protocol Pure-Java driver.
 The JDBC API consists of various classes and interfaces that enable Java
applications to interact with databases.
 The classes and interfaces of the JDBC API are defined in the java.sql and
javax.sql packages.
 You can load a driver and register it with the driver manager either
programmatically or manually.

146 Core Java | JDBC | Muralidhar


Summary (continued)

 Two ways to load and register a driver programmatically are:


– Using the Class.forName() method
– Using the registerDriver() method

 You can add the driver name to the jdbc.drivers system property to load
and register a JDBC driver manually.
 A Connection object establishes a connection between a Java application
and a database.
 A Statement object sends requests to and retrieves results from a
database.
 You can insert, update, and delete data from a table using the DML
statements in Java applications.
147 Core Java | JDBC | Muralidhar
Summary (continued)

 You can create, alter, and drop tables from a database using the DDL
statements in Java applications.
 A ResultSet object stores the result retrieved from a database when a
SELECT statement is executed.
 You can create various types of ResultSet objects such as read only,
updatable, and forward only.

148 Core Java | JDBC | Muralidhar


Review questions

1. A JDBC __________ is a software that a Java application uses to access


a database.
a. Driver
b. DSN
c. CLI
d. DriverManager

2. _ _ _ _ _ interface enables you to establish a connection between a Java


application and the database.
a. ResultSet
b. Connection
c. Statement
d. SQL
149 Core Java | JDBC | Muralidhar
Review questions (continued)

3. _ _ _ _ _ manages various JDBC drivers?


a. ManagerDriver
b. Driver
c. DriverManager
d. ODBC Driver

4. _ _ _ _ _ _sends requests to and retrieves result from a database.


a. ResultSet
b. Statement
c. Connection
d. next()

150 Core Java | JDBC | Muralidhar


Questions

151 Core Java | JDBC | Muralidhar


Day Summary

At the end of Day we see that you are now able to:
 Find more information about Threads
 Explain and define JDBC

152 Core Java | JDBC | Muralidhar


THANK YOU

153 Core Java | JDBC | Muralidhar

You might also like