The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Hartati Zulfikri, 2021-06-28 00:13:57

nota modul dfp4033

nota modul dfp4033

BorderLayout

 Used to arrange the components in five regions: north, south, east, west and center.

 Each region (area) may contain one component only. It is the default layout of frame
or window.

The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:
1. BorderLayout(): creates a border layout but with no gaps between the components.
2. JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }}

Integrative Programming Technologies | 50

BoxLayout
 A box layout organizes components horizontally (in one row) or vertically (in one
column)
 Components are placed top-to-bottom or left-to-right in the order in which they are
added to the container

Fields of BoxLayout class
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the
components with the given axis.

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample1 b=new BoxLayoutExample1();
22. }
23. }

Integrative Programming Technologies | 51

3.0 EVENT HANDLING

3.1 Write program using the Event Handling with GUI components
3.1.1 Define Event Handling and identify its uses

Now that we know how to design the "look" of a window by placing components on it. Next,
we need to make the window respond properly to the user interaction. The techniques are
based on something called "Event Handling". In JAVA, we handle events by writing
"Listeners" (also known as event handlers).

In the previous set of notes, we have seen how to create a GUI with various types of
components. However, none of the components on the window seem to respond to the
user interactions. In order to get the interface to "work" we must make it respond
appropriately to all user input such as clicking buttons, typing in text fields, selecting items
from list boxes etc... To do this, we must investigate events.

What is an event ?
An event is something that happens in the program based on some kind of triggering
input.
Typically caused (i.e., generated) by user interaction (e.g., mouse press, button
press, selecting from a list etc...)

 the component that caused the event is called the source.

Can also be generated internally by the program.

How are Events Used in JAVA ?
Events are objects, so each type of event is represented by a distinct class (similar to
the way exceptions are distinct classes)
Low-level events represent window-system occurrences or low-level input such as
mouse and key events and component, container, focus, and window events.
Some events may be ignored, some may be handled. We will write event handlers
which are known as listeners.

Integrative Programming Technologies | 52

Here is a picture that describes the process of user interaction with a GUI through events:

Basically...here's how it works:
1. The user causes an event (e.g., click button, enter text, select list item etc...)
2. The JAVA VM invokes (i.e., triggers) the appropriate event handler (if it has been
implemented and registered). This invocation really means that a method is called to
handle the event.
3. The code in the event handling method changes the model in some way.
4. Since the model has changed, the interface will probably also change and so
components should be updated.

So when an event is generated, JAVA needs to go to the appropriate method in your code to
handle the event. How does JAVA know which method to call ? We will register each event-
handler so that JAVA can call them when the events are generated. These event-handlers
are called listeners (or callbacks).
A listener :

acts on (i.e., handle) the event notification.
must be registered so that it can be notified about events from a particular source.
can be an instance of any class (as long as the class implements the appropriate
listener interface)

Integrative Programming Technologies | 53

So ... when creating a GUI, we must:
Decide what types of events we want to handle
Inform JAVA which ones we want to handle by registering the event handlers (i.e.,
the listeners)
Write the event handling code for each event

4.1.2 Explain Event Listener in Java program
The Event listener represent the interfaces responsible to handle events. Java provides us
various Event listener classes but we will discuss those which are more frequently used.
Every method of an event listener method has a single argument as an object which is
subclass of EventObject class. For example, mouse event listener methods will accept
instance of MouseEvent, where MouseEvent derives from EventObject.

Delegation Event Model

3.1.3 Summarize events and their respective components and interfaces
There are many types of events that are generated and commonly handled. Here is a table
of some of the common events. The table gives a short description of when the events may
be generated, gives the interface that must be implemented by you in order for you to
handle the events and finally lists the necessary methods that need to be implemented.

Integrative Programming Technologies | 54

Event Classes Description Listener Interface Methods that ‘you’ must write
ActionEvent actionPerformed(ActionEvent e)
generated when ActionListener
MouseEvent mouseClicked(MouseEvent e)
button is pressed, mouseEntered(MouseEvent e)
KeyEvent mouseExited(MouseEvent e)
ItemEvent menu-item is selected, mousePressed(MouseEvent e)
ChangeEvent component
list-item is double mouseReleased(MouseEvent e)
keyPressed(KeyEvent e)
clicked keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
generated when MouseListener itemStateChanged(ItemEvent e)

mouse is dragged, stateChanged(ChangeEvent e)

moved,clicked,pressed valueChanged(ListSelectionEvent e)

or released and also windowOpened(WindowEvent e)
windowClosed(WindowEvent e)
when it enters or exit windowClosing(WindowEvent e)
windowActivated(WindowEvent e)
a component windowDeActivated(WindowEv ent
e) windowIconified(WindowEvent
generated when input KeyListener e) windowD
is received from changedUpdate(DocumentEvent e)
keyboard insertUpdate(DocumentEvent e)
removeUpdate(DocumentEvent e)
generated when ItemListener
caretUpdate(CaretEvent e)
check-box or list item

is clicked

value of a component ChangeListener
such as a JSlider has
changed

ListSelectionEvent selecting (click or double ListSelectionListener
click) a list item

WindowEvent generated when WindowListener

window is activated,

deactivated,

deiconified, iconified,

opened or closed

DocumentEvent changes have been DocumentListener

made to a text

document such as

insertion, removal in an

editor

CaretEvent moving cursor (caret) in CaretListener
a text-related
component such as a
JTestFiled

Integrative Programming Technologies | 55

FocusEvent generated when FocusListener focusGained(FocusEvent e)
focusLost(FocusEvent e)
component gains or

loses keyboard focus

So, if you want to handle a button press in your program, you need to write an
actionPerformed()method:
public void actionPerformed(ActionEvent e)
{ //Do what needs to be done when the button is clicked }
If you want to have something happen when the user presses a particular key on the
keyboard, you need to write a keyPressed() method:
public void keyPressed(KeyEvent e)
{ //Do what needs to be done when a key is pressed }

Integrative Programming Technologies | 56

3.1.4 Write program using the Event Handling with GUI components
The following diagram shows how we setup event handling for a button click and how the
various parts of the table above interact with each other to allow us as programmers to
respond to this user event.

Example : Using the ActionListener Interface
The ActionListener listener interface is used for receiving action events. Any classes
interested in processing action events should implement this interface. An object created
with the class is registered with a component using that component’s addActionListener()
method. When the action event occurs on the component we have registered
the actionPerformed(ActionEvent e) method of the object is invoked.
In the following example we create a single button and change its label each time the
button is clicked.

Integrative Programming Technologies | 57

1. import javax.swing.JFrame; // An interactive window
2. import javax.swing.JButton; // An interactive button
3. import java.awt.event.*; // AWT event package
4.
5. public class OurActionListener implements ActionListener {
6. JButton btn;
7. int count;
8.
9. public static void main (String[] args) {
10. OurActionListener oal = new OurActionListener();
11. oal.start();
12. }
13.
14. public void start() {
15. JFrame jf = new JFrame("Using the ActionListener Interface");
16. // Create a JButton using our instance variable
17. btn = new JButton("I have been clicked " + count + " times.");
18. // Register the JButton with our OurActionListener object
19. btn.addActionListener(this);
20. // Add JButton to frame, set size and display it
21. jf.add(btn);
22. jf.setBounds(300, 200, 568, 218);
23. jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
24. jf.setVisible(true);
25. }
26.
27. // Implement the only method from the ActionListener Interface
28. public void actionPerformed(ActionEvent e) {
29. count++;
30. btn.setText("I have been clicked " + count + " times.");
31. }
32. }

The following screesnshot shows the results of compiling and running the OurActonListener
class and pressing the button 4 times. We implement the ActionListener on our
OurActionListener top level class. We create an instance of OurActionListener and call the
start() method with this object. We then create a frame and a button and register the
button with the invoking object (this), which is our OurActionListener object called oal. We
then set up our frame and implement the only method within the ActionListener interface
which is actionPerformed(ActionEvent e). Every time we press the button this method is
invoked and we add to a count and pass this to the button’s label so we can see it change
each time.

Integrative Programming Technologies | 58

But how does this work when we have multiple buttons and we want each to do something
different? We can't have more than one version of the actionPerformed(ActionEvent e)
method in the class or the compiler gets upset. When we have more than one component
within a class that uses the same listener implementation method and we want that method
to do different things for each component then we have to put each occurrence of the
method within its own inner class or separate each one out using the passed EventObject.

In the following example we get around the above conundrum using inner classes. We
create two buttons that use separate variables and change the label for the button in
question each time it is clicked.

1. import javax.swing.JFrame; // An interactive window

2. import javax.swing.JButton; // An interactive button

3. import java.awt.*; // AWT

4. import java.awt.event.*; // AWT event package

5.

6. public class OurActionListener2 {

7. JButton btn1;

8. JButton btn2;

9. int count1;

10. int count2;

11.

12. public static void main (String[] args) {

13. OurActionListener2 oal2 = new OurActionListener2();

14. oal2.start();

15. }

16.

17. public void start() {

18. JFrame jf = new JFrame("Using Multiple Components With The ActionListener

19. Interface");

20. // Create 2 JButtons using our instance variables

21. btn1 = new JButton("Button 1. I have been clicked " + count1 + " times.");

22. btn2 = new JButton("Button 2. I have been clicked " + count2 + " times.");

23. // Register our JButton via different inner classes

24. btn1.addActionListener(new addActionListener1());

25. btn2.addActionListener(new addActionListener2());

26. // Add buttons directly to two regions of BorderLayout of frame,setsize

27. jf.add(BorderLayout.NORTH, btn1);

28. jf.add(BorderLayout.SOUTH, btn2);

29. jf.setBounds(300, 200, 568, 218);

30. jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

31. jf.setVisible(true);

32. }

33. // Inner class 1

34. class addActionListener1 implements ActionListener {

35. public void actionPerformed(ActionEvent e) {

36. count1++;

37. btn1.setText("I have been clicked " + count1 + " times.");

38. }

39. }

40. // Inner class 2

41. class addActionListener2 implements ActionListener {

42. public void actionPerformed(ActionEvent e) {

43. count2++;

44. btn2.setText("I have been clicked " + count2 + " times.");

45. }

46. }

47. } Integrative Programming Technologies | 59

The following screenshot shows the results of compiling and running
the OurActionListener2 class and pressing the top button 5 times and the bottom button 3
times. This time we don't implement the ActionListener on our OurActionListener2 top level
class but instead create two inner classes which each implement ActionListener. We create
an instance of OurActionListener2 and call the start() method with this object. We create
our frame and two buttons and register these separately with our inner classes. We then set
up our frame, adding our buttons to the NORTH and SOUTH regions and implement the only
method within the ActionListener interface within each of our inner classes. Every time we
press a button we invoke the actionPerformed(ActionEvent e) method on the inner class
that that particular button is registered with. Within the method we add to a count and pass
this to the button's label so we can see it change each time.

Inner class listeners can be shortened using anonymous inner class. An anonymous inner
class is a inner class without a name. It combines declaring an inner class and creatinf an
instance of the class in one step.
Anonymous class syntax

Integrative Programming Technologies | 60

We modify inner class example to anonymous inner class

1. import javax.swing.JFrame; // An interactive window

2. import javax.swing.JButton; // An interactive button

3. import java.awt.*; // AWT

4. import java.awt.event.*; // AWT event package

5.

6. public class OurActionListener3 {

7. JButton btn1;

8. JButton btn2;

9. int count1;

10. int count2;

11.

12. public static void main (String[] args) {

13. OurActionListener3 oal3 = new OurActionListener3();

14. oal3.start();

15. }

16.

17. public void start() {

18. JFrame jf = new JFrame("Using Multiple Components With The ActionListener

19. Interface");

20. // Create 2 JButtons using our instance variables

21. btn1 = new JButton("Button 1. I have been clicked " + count1 + " times.");

22. btn2 = new JButton("Button 2. I have been clicked " + count2 + " times.");

23.

24. // create and register anonymous inner class listener

25. btn1.addActionListener(new ActionListener()

26. {

27. public void actionPerformed(ActionEvent e) {

28. count1++;

29. btn1.setText("I have been clicked " + count1 + " times.");

30. }});

31.

32. btn2.addActionListener(new ActionListener()

33. {

34. public void actionPerformed(ActionEvent e) {

35. count1++;

36. btn1.setText("I have been clicked " + count1 + " times.");

37. }});

38.

39. // Add buttons directly to two regions of BorderLayout of frame, setsize

40. jf.add(BorderLayout.NORTH, btn1);

41. jf.add(BorderLayout.SOUTH, btn2);

42. jf.setBounds(300, 200, 568, 218);

43. jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

44. jf.setVisible(true);

45. }

46. }

Integrative Programming Technologies | 61

Example using ActionListener and ItemListener

1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class SimpleAWT extends JFrame {
5. private JButton button = new JButton("Push Me!");
6. private JCheckBox checkbox = new JCheckBox("Check Me!");
7. String colour[]={"Red","Blue","Green"};
8. private JComboBox choice = new JComboBox(colour);
9. private JLabel label = new JLabel("Pick something!");

10. SimpleAWT()
11. {
12. button.addActionListener(new ActionListener()
13. { public void actionPerformed(ActionEvent e) {
14. if (e.getSource() == button)
15. label.setText("The Button was pushed.");
16. }
17. });

18. checkbox.addItemListener(new ItemListener()
19. {public void itemStateChanged(ItemEvent e) {
20. if (e.getSource() == checkbox)
21. label.setText("The Checkbox is now " + checkbox.isSelected() );
22. }
23. });

24. choice.addItemListener(new ItemListener()
25. {public void itemStateChanged(ItemEvent e)
26. { if (e.getSource() == choice)
27. label.setText(choice.getSelectedItem() + " was selected " );
28. }
29. });

30. setLayout(new BorderLayout());
31. JPanel panel = new JPanel();
32. panel.add(button);
33. panel.add(checkbox);
34. panel.add(choice);
35. add(label, "Center");
36. add(panel, "South");
37. setTitle("Example of Event Handling");
38. setVisible(true);
39. setSize(300,150);
40. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
41. }

42. public static void main(String args[]){
43. new SimpleAWT();
44. }
45. }

Integrative Programming Technologies | 62

Example using KeyListener

1. import java.awt.*;

2. import java.awt.event.*;

3.

4. // An AWT GUI program inherits from the top-level container java.awt.Frame

5. public class KeyEventDemo extends Frame implements KeyListener {

6. // This class acts as KeyEvent Listener

7.

8. private TextField tfInput; // Single-line TextField to receive tfInput key

9. private TextArea taDisplay; // Multi-line TextArea to taDisplay result

10.

11. // Constructor to setup the GUI components and event handlers

12. public KeyEventDemo() {

13. setLayout(new FlowLayout()); // "super" frame sets to FlowLayout

14.

15. add(new Label("Enter Text: "));

16. tfInput = new TextField(10);

17. add(tfInput);

18. taDisplay = new TextArea(5, 40); // 5 rows, 40 columns

19. add(taDisplay);

20.

21. tfInput.addKeyListener(this);

22. // tfInput TextField (source) fires KeyEvent.

23. // tfInput adds "this" object as a KeyEvent listener.

24.

25. setTitle("KeyEvent Demo"); // "super" Frame sets title

26. setSize(400, 200); // "super" Frame sets initial size

27. setVisible(true); // "super" Frame shows

28. }

29.

30. // The entry main() method

31. public static void main(String[] args) {

32. new KeyEventDemo(); // Let the constructor do the job

33. }

34.

35. /** KeyEvent handlers */

36. // Called back when a key has been typed (pressed and released)

37. @Override

38. public void keyTyped(KeyEvent evt) {

39. taDisplay.append("You have typed " + evt.getKeyChar() + "\n");

40. }

41. public void keyPressed(KeyEvent evt) {}

42.

43. public void keyReleased(KeyEvent evt) {}

44. }

Integrative Programming Technologies | 63

Example using MouseListener and ActionListener

1. import javax.swing.*;
2. import java.awt.event.*;
3. class PopupMenuExample
4. {
5. PopupMenuExample(){
6. final JFrame f= new JFrame("PopupMenu Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. final JPopupMenu popupmenu = new JPopupMenu("Edit");
11. JMenuItem cut = new JMenuItem("Cut");
12. JMenuItem copy = new JMenuItem("Copy");
13. JMenuItem paste = new JMenuItem("Paste");
14. popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);

15. f.addMouseListener(new MouseAdapter() {
16. public void mouseClicked(MouseEvent e) {
17. popupmenu.show(f , e.getX(), e.getY());
18. }});
19. cut.addActionListener(new ActionListener(){
20. public void actionPerformed(ActionEvent e) {
21. label.setText("cut MenuItem clicked.");
22. } });
23. copy.addActionListener(new ActionListener(){
24. public void actionPerformed(ActionEvent e) {
25. label.setText("copy MenuItem clicked.");
26. } });
27. paste.addActionListener(new ActionListener(){
28. public void actionPerformed(ActionEvent e) {
29. label.setText("paste MenuItem clicked.");
30. } });
31. f.add(label); f.add(popupmenu);
32. f.setSize(400,400);
33. f.setLayout(null);
34. f.setVisible(true);
35. }
36. public static void main(String args[])
37. {
38. new PopupMenuExample();
39. } }

Integrative Programming Technologies | 64

Example using ListSelectionListener

1. import javax.swing.*;
2. import javax.swing.event.ListSelectionListener;
3. import javax.swing.event.ListSelectionEvent;
4. import java.awt.*;

5. class Frame extends JFrame implements ListSelectionListener{

6. private JList jl;
7. private JButton jb;
8. private String[] names = {"Nokia","Samsung","Htc","Sony","Apple","Sony

Ericsson","Philips","Toshiba","Micromax","Lenovo","Celkon","Casio","Acer"};
9. Frame()
10. { setTitle("JList with ListSelectionListener");
11. setLayout(new FlowLayout());
12. setJList();
13. setJListAction();
14. setSize(700,250);
15. setVisible(true);
16. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }

18. private void setJList()
19. { jl = new JList(names);
20. JScrollPane js = new JScrollPane(jl);
21. js.setPreferredSize(new Dimension(200,200));
22. add(js);
23. jb = new JButton("Select any one brand");
24. add(jb);
25. }

26. private void setJListAction()
27. { jl.addListSelectionListener(this);
28. }

29. public void valueChanged(ListSelectionEvent eve)
30. { int returns = jl.getSelectedIndex();
31. if(returns != -1)
32. { jb.setText("Your selection : "+names[returns]);}
33. else if(returns == -1)
34. {
35. jb.setText("Select any one brand");
36. }}}
37. public class Javaapp {
38. public static void main(String[] args) {
39. Frame fr = new Frame();
40. }
41. }

Integrative Programming Technologies | 65

4.0 JAVA DATABASE CONNECTIVITY (JDBC)

4.1 Apply JDBC Connectivity
4.1.1 Explain JDBC and ODBC database access

JDBC and ODBC, both are the API (Application Programming Interface) that help the
applications on the client side to access the database on the server side. The RDBMS
vendors provide ODBC or JDBC drivers so that their database can be accessed by the
applications on client side.

The point that fundamentally differentiates JDBC and ODBC is that JDBC is language
dependent and it is Java specific whereas, the ODBC is a language independent. Let us see in
how many aspects the does JDBC and ODBC differs from each other with the help of
comparison chart shown below.

Comparison Chart

ODBC JDBC

ODBC Stands for Open Database JDBC Stands for java database
Connectivity. connectivity.

Introduced by Microsoft in 1992. Introduced by SUN Micro Systems in
1997.

We can use ODBC for any language like We can use JDBC only for Java languages.
C,C++,Java etc.

We can choose ODBC only windows We can Use JDBC in any platform.
platform.

Mostly ODBC Driver developed in native JDBC Stands for java database
languages like C,C++. connectivity.

For Java applications it is not recommended For Java application it is highly
to use ODBC because performance will be recommended to use JDBC because
down due to internal conversion and there we no performance & platform
applications will become platform dependent problem.
Dependent.

ODBC is procedural. JDBC is object oriented.

Definition of ODBC

ODBC is Open Database Connectivity. ODBC is an API that acts as an interface between an
application on the client side and the database on the server side. Microsoft introduced
ODBC in the year 1992.

Integrative Programming Technologies | 66

ODBC helps an application to access the data from the database. An application written in
any language can use ODBC to access different types of databases and hence, it is said to be
language and platform independent. Like JDBC, ODBC also provides ODBC drivers that
convert the request of application written in any language into the language understandable
by databases.

ODBC is most widely used and understands many different programming languages. But its
code is complex and hard to understand.

Definition of JDBC

Java Database Connectivity (JDBC) is an application programming interface i.e. (API). JDBC
was released as a part of Java development Kit (JDK) 1.1. in the year 1996 by SUN Microsoft.
It is built the basis of ODBC and hence, some basics of ODBC retain in JDBC.

It is a standard interface between any Java application and different databases. The function
of JDBC is to help the Java-based application to access different types of databases. JDBC
provide methods to query database, and it can also be used to update the database. JDBC
provide JDBC drivers that converts the request from Java application on client side to the
language that database understands.

As JDBC is language and platform specific, Java application can use JDBC-to-ODBC bridge to
communicate with ODBC adaptable databases. Unlike ODBC, JDBC has easy coding but, it is
only limited to Java only.

4.1.2 Identify JDBC driver type

JDBC Driver is a software component that enables java application to interact with the database.

There are FOUR types of JDBC drivers :

1) Type – 1 : JDBC-ODBC Bridge driver (Bridge)
2) Type – 2 : Native-API/partly Java Driver (Native)
3) Type – 3 : All Java/Net-protocol driver (Middleware)
4) Type – 4 : All Java/Native-protocol driver (Pure)

1) JDBC-ODBC Bridge driver
 In Type – 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine.
 Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
 The Type – 1 driver translates all JDBC calls into ODBC calls and sends them to ODBC driver.
 ODBC is a generic API.
 The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other
alternative is available.

Integrative Programming Technologies | 67

Advantages
 Easy to use
 Can be easily connected to any database

Disadvantages
 The Bridge driver is not written fully in Java, Type 1 drivers are not portable.
 Performance degraded because JDBC method call is converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client machine.
 Not good for the web.
 It is the slowest of all driver types.

2) Native-API/partly Java driver
 Type 2 drivers convert JDBC calls into database-specific calls.
 This driver is specific to a particular database.
 The vendor-specific driver must be installed on each client machine.
 If we change the database, we have to change the native API because it is database
specific.
 It is not written entirely in Java.

Integrative Programming Technologies | 68

Advantages
 Performance increases with a Type 2 driver as compare to Type 1 driver, because it
eliminate ODBC’s overhead.

Disadvantages
 The Native driver needs to be installed on the each client machine.
 The vendor client library needs to be installed on client machine.
 If we change the Database we have to change the native API as it is specific to a database.
 It is platform dependent.

3) Pure Java/Network-protocol/Middleware driver
 Type 3 driver is used three tier approach to access database.
 It uses middleware (application server) that converts JDBC calls directly or indirectly into
the vendor specific database protocol.
 It is fully written in Java.

Integrative Programming Technologies | 69

Advantages

 This driver is server-based, so there is no need for any vendor database library to be present
on client machines.

 It is portable because it is fully written in Java.
 It is very flexible allow access to multiple databases using one driver.
 They are the most efficient amongst all driver types.
 The midlleware server can provide typical middleware services like caching, load balancing,

logging and auditing.

Disadvantages

 Network support is required on client machine.
 Maintenance of network protocol driver becomes costly because it requires database

specific coding to be done in the middle tier.
 It requires another server application to install and maintain.

4) Database-protocol/Pure Java driver
 Type 4 driver is an all Java driver which connects directly to the database. It is also known
as Thin Driver.
 It is a database driver implementation that converts JDBC calls directly into a vendor
specific database protocol.
 The database protocol is vendor specific, the JDBC client requires separate drivers, usually
vendor supplied, to connect to different types of databases.
 It is fully written in Java language.

Integrative Programming Technologies | 70

Advantages
 It is platform dependent.
 The client application connects directly to the database server. No translation or middleware
layers are used, performance is quite good.
 No software is requires at client side or server side.

Disadvantages
 Drivers depend on the database.

Integrative Programming Technologies | 71

4.1.3 Explain JDBC Statement Objects

Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties
that enable you to send SQL or PL/SQL commands and receive data from your database.

They also define methods that help bridge data type differences between Java and SQL data
types used in a database.

The following table provides a summary of each interface's purpose to decide on the
interface to use.

Interfaces Recommended Use

Statement Use this for general-purpose access to your database. Useful when
you are using static SQL statements at runtime. The Statement
interface cannot accept parameters.

PreparedStatement Use this when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.

CallableStatement Use this when you want to access the database stored procedures.
The CallableStatement interface can also accept runtime input
parameters.

a. The Statement Objects

Creating Statement Object
Before you can use a Statement object to execute a SQL statement, you need to create one
using the Connection object's createStatement( ) method, as in the following example :

Integrative Programming Technologies | 72

Once you've created a Statement object, you can then use it to execute an SQL statement
with one of its three execute methods.

 boolean execute (String SQL): Returns a boolean value of true if a ResultSet object
can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL
statements or when you need to use truly dynamic SQL.

 int executeUpdate (String SQL): Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for
which you expect to get a number of rows affected - for example, an INSERT, UPDATE,
or DELETE statement.

 ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.

Closing Statement Object
Just as you close a Connection object to save database resources, for the same reason you
should also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first, it
will close the Statement object as well. However, you should always explicitly close the
Statement object to ensure proper cleanup.

Integrative Programming Technologies | 73

Example Of Statement Object

//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";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{

//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

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

//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Employees set age=30 WHERE id=103";

// Let us check if it returns a true Result Set or not.
Boolean ret = stmt.execute(sql);
System.out.println("Return value is : " + ret.toString() );

// Let us update age of the record with ID = 103;
int rows = stmt.executeUpdate(sql);
System.out.println("Rows impacted : " + rows );

// Let us select all the records and display them.
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();

Integrative Programming Technologies | 74

stmt.close();
conn.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

b. The Prepared Statement Object

The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object

Integrative Programming Technologies | 75

All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the parameters.
Closing PreparedStatement Object
Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it
will close the PreparedStatement object as well. However, you should always explicitly close
the PreparedStatement object to ensure proper cleanup.

Integrative Programming Technologies | 76

Example Of Prepared Statement

//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";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
try{

//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

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

//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "UPDATE Employees set age=? WHERE id=?";
stmt = conn.prepareStatement(sql);

//Bind values into the parameters.
stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID

// Let us update age of the record with ID = 102;
int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );

// Let us select all the records and display them.
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();

Integrative Programming Technologies | 77

conn.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. The Callable Statement

Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database
stored procedure.
Creating CallableStatement Object
Suppose, you need to execute the following MySQL stored procedure :

Integrative Programming Technologies | 78

Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all the three.

Here are the definitions of each −

Parameter Description

IN A parameter whose value is unknown when the SQL statement is
created. You bind values to IN parameters with the setXXX() methods.

OUT A parameter whose value is supplied by the SQL statement it returns.
You retrieve values from theOUT parameters with the getXXX() methods.

INOUT A parameter that provides both input and output values. You bind
variables with the setXXX() methods and retrieve values with the
getXXX() methods.

The following code snippet shows how to employ the Connection.prepareCall() method to
instantiate a CallableStatement object based on the preceding stored procedure

The String variable SQL, represents the stored procedure, with parameter placeholders.
Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement, or you will receive
an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type
you are binding.

Integrative Programming Technologies | 79

When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method
binds the JDBC data type, to the data type that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it
will close the CallableStatement object as well. However, you should always explicitly close
the CallableStatement object to ensure proper cleanup.

Example Of Callable Statement

//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";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{

//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

Integrative Programming Technologies | 80

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

//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call getEmpName (?, ?)}";
stmt = conn.prepareCall(sql);

//Bind IN parameter first, then bind OUT parameter
int empID = 102;
stmt.setInt(1, empID); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);

//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();

//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID:" +

empID + " is " + empName);
stmt.close();
conn.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

Integrative Programming Technologies | 81

4.1.4 Use JDBC for database connectivity by applying the appropriate steps

a. Import the packages
This is for making the JDBC API classes immediately available to the application program.
The following import statement should be included in the program irrespective of the JDBC
driver being used:

import java.sql.*;

For individual JDBC API classes imports:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

b. Load the JDBC driver

To begin with, you first need load the driver or register it before using it in the program.
Registration is to be done once in your program. You can register a driver using
Class.forName() method.

 Class.forName() : Here we load the driver’s class file into memory at the runtime. No
need of using new or creation of object .

 The following example uses Class.forName() to load the Oracle driver –
Class.forName(“oracle.jdbc.driver.OracleDriver”);

 The following example uses Class.forName() to load the MySQL driver –
Class.forName(“com.mysql.jdbc.Driver”);

Database Driver Class Source
Access sun.jdbc.odbc.JdbcOdbcDriver Already in (bundled in JDK)
MySQL com.mysql.jdbc.Driver Website (mysqljdbc.jar)
Oracle Oracle.jdbc.driver.OracleDriver Website (classes12.jar)

Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put the
JDBC Jar file in the classpath, and then JDBC driver manager can detect and load the driver
automatically.

Integrative Programming Technologies | 82

c. Define the connection

To define the connection is declaring the information for the connection. Example code
snippet using MySQL database.

String USER = "username";
String PASS = "password";
Sring DB_URL = “jdbc:mysql://localhost:3306/Employees”;

which is the database URL string in the following format:

Database URL Pattern

Access jdbc:odbc:dataSource

MySQL Jdbc:mysql://hostname/dbname

Oracle Jdbc:oracle:thin@hostname:portNumber:databaseName

d. Establish the Database Connection
This requires using the DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database as follows:

Connection conn;
conn = DriverManager.getConnection(DB_URL,USER,PASS);

e. Create a Statement Object
Statement objects are created from active Connection objects. For example :

Statement stmt = conn.createStatement();
With a statement object, you can issue SQL calls directly to the database.
f. Execute a Query
This requires using an object of type Statement or PreparedStatement for building and
submitting an SQL statement to the database as follows:

System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

Integrative Programming Technologies | 83

If there is an SQL UPDATE,INSERT or DELETE statement required, then following code
snippet would be required:

System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "DELETE FROM Employees";
ResultSet rs = stmt.executeUpdate(sql)

g. Process the results
This step is required in case you are fetching data from the database. You can use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set as follows:

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);
}

h. Close the connections
You should explicitly close all database resources versus relying on the JVM's garbage
collection as follows:

rs.close();
stmt.close();
conn.close();

Integrative Programming Technologies | 84

4.2 Use SQL in JDBC
4.2.1 Handling SQL statements in JDBC
In this subtopic you are going to learn insert, update, delete or select rows using JDBC.
While developing Java Application it is almost the very important part. Most of the
application lies on Database and they use Table to save and retrieve records. It is very
important to have sound knowledge over data manipulation, if you want to be a perfect java
developer. The following example sows a simple program that will easily demonstrate
insert, update, delete and search record in table using JDBC.

a. INSERT statement
Example

Integrative Programming Technologies | 85

b. SELECT statement
Once you inserted record you can retrieve record using ResultSet Object of JDBC. Here is the
complete programming example of retrieving data from MySQL using JDBC.

Integrative Programming Technologies | 86

Integrative Programming Technologies | 87

c. UPDATE statement and DELETE statement
Updating and Deleting Records in MySQL using JDBC is so simple. You have to follow same
procedure and execute update or delete command.

Integrative Programming Technologies | 88

Integrative Programming Technologies | 89


Click to View FlipBook Version