[go: up one dir, main page]

0% found this document useful (0 votes)
8 views145 pages

Java_UNIT_4

The document outlines the syllabus for a BCA IV semester course, covering Java Swing fundamentals, JDBC, applets, and GUI components. It details the lifecycle of applets, comparisons between AWT and Swing, and various layout managers in Java. Additionally, it provides examples of commonly used components like JButton, JLabel, JCheckBox, and JRadioButton, along with their constructors and methods.

Uploaded by

chirag30n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views145 pages

Java_UNIT_4

The document outlines the syllabus for a BCA IV semester course, covering Java Swing fundamentals, JDBC, applets, and GUI components. It details the lifecycle of applets, comparisons between AWT and Swing, and various layout managers in Java. Additionally, it provides examples of commonly used components like JButton, JLabel, JCheckBox, and JRadioButton, along with their constructors and methods.

Uploaded by

chirag30n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

UNIT 4

BCA IV SEM
Syllabus
 Swings Fundamentals: Components (JLabel and ImageIcon, using
swing Buttons (JButton, JToggleButton, JCheckBox, JRadioButton),
JTextField, JScrollPane, JList, JComboBox) and Containers, Layout
managers, event delegation Model, event handling (event sources, event
listeners, event classes and interfaces, adapter classes).
 JDBC: JDBC Architecture, JDBC Drivers, Connection, Statement,
Prepared Statement, Result set, Connecting to the Database using JDBC.
Applets
 Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at
client side.
Advantage of Applet
 There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.
Lifecycle of Java Applet
Lifecycle methods for Applet
 public void init(): is used to initialized the Applet. It is invoked
only once.
 public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked
only once.
How to run an Applet?

 There are two ways to run an applet


 By html file.
 By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
myapplet.html
Java AWT
 Java AWT (Abstract Window Toolkit) is an API to develop
GUI or window-based applications in java.
 Java AWT components are platform-dependent i.e.
components are displayed according to the view of
operating system. AWT is heavyweight i.e. its components
are using the resources of OS.
 The java.awt package provides classes for AWT api such as
TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List etc.
Swing
 Swing is a lightweight Java graphical user interface (GUI) that is used to
create various applications.
 Swing has platform-independent components. It enables the user to
create buttons and scroll bars.
 Swing includes packages for creating desktop applications in Java. Swing
components are written in Java language.
Applet VS Swing
S.NO AWT Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
1.
applications in Java and is used to create various applications.

The components of Java AWT are heavy The components of Java Swing are light
2.
weighted. weighted.

Java AWT has comparatively less functionality Java Swing has more functionality as
3.
as compared to Swing. compared to AWT.

The execution time of AWT is more than The execution time of Swing is less than
4.
Swing. AWT.

The components of Java AWT are platform The components of Java Swing are platform
5.
dependent. independent.

MVC(Model-View-Controller) pattern is not


6. MVC pattern is supported by Swing.
Applet VS Swing
S.NO AWT Swing

AWT provides comparatively less powerful Swing provides more powerful


7.
components. components.

Swing components requires javax.swing


8 AWT components require java.awt package
package

AWT is a thin layer of code on top of the Swing is much larger swing also has very
9
operating system. much richer functionality.

Swing is also called as JFC(java Foundation


10 AWT stands for Abstract windows toolkit .
classes). It is part of oracle’s JFC.

Using AWT , you have to implement a lot of


11 Swing has them built in.
things yourself .
Swings Fundamentals
 Swing in java is part of Java foundation class which is lightweight and
platform independent.
 It is used for creating window based applications. It includes
components like button, scroll bar, text field etc.
 Putting together all these components makes a graphical user
interface.
 It is a part of the JFC( Java Foundation Classes).
 It is build on top of the AWT API and entirely written in java.
 It is platform independent unlike AWT and has lightweight
components.
Swing Features
 Light Weight − Swing components are independent of native
Operating System's API as Swing API controls are rendered mostly
using pure JAVA code instead of underlying operating system calls.
 Rich Controls − Swing provides a rich set of advanced controls like
Tree, TabbedPane, slider, colorpicker, and table controls.
 Highly Customizable − Swing controls can be customized in a very
easy way as visual apperance is independent of internal
representation.
 Pluggable look-and-feel − SWING based GUI Application look
and feel can be changed at run-time, based on available values.
Container Class
 Any class which has other components in it is called as a container
class. For building GUI applications at least one container class is
necessary.
Following are the three types of container classes:
 Panel – It is used to organize components on to a window
 Frame – A fully functioning window with icons and titles
 Dialog – It is like a pop up window but not fully functional like the
frame
Difference Between AWT and Swing
Hierarchy of Java Swing classes
Commonly used Methods of Component class
Java Swing Examples
There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
Example of Swing by Association
Simple example of Swing by inheritance
Java JButton
Java JLabel

 The object of JLabel class is a component for placing text in a


container.
 It is used to display a single line of read only text.
 The text can be changed by an application but a user cannot
edit it directly.
 It inherits JComponent class.
Commonly used Constructors in JLables
Commonly used Methods in JLables
Java JLabel Example
Java JLabel Example with ActionListener
How to change TitleBar icon Swing

 The setIconImage() method of Frame class is used to change the icon


of Frame or Window.
 It changes the icon which is displayed at the left side of Frame or
Window.
 The Toolkit class is used to get instance of Image class
in AWT and Swing.
 Toolkit class is the abstract super class of every implementation in
the Abstract Window Toolkit(AWT).
 Subclasses of Toolkit are used to bind various components. It
inherits Object class.
Example to change TitleBar icon in Java AWT
Example to change TitleBar icon in Java Swing
Java JButton

 The JButton class is used to create a labeled button that has


platform independent implementation.
 The application result in some action when the button is
pushed.
 It inherits AbstractButton class.
Commonly used Constructors in JButton
Commonly used Methods of AbstractButton class in
JButton
Java JButton Example
Java JButton Example with ActionListener
Example of displaying image on the button
Java JToggleButton
 JToggleButton is used to create toggle button, it is two-states button to
switch on or off.
 Nested Classes
Constructors in JToggleButton
Methods in JToggleButton
JToggleButton Example
Java JCheckBox

 The JCheckBox class is used to create a checkbox.


 It is used to turn an option on (true) or off (false).
 Clicking on a CheckBox changes its state from "on" to "off" or
from "off" to "on ".
 It inherits JToggleButton class.
Commonly used Constructors in JCheckBox
Commonly used Methods in JCheckBox
Java JCheckBox Example
Java JCheckBox Example with ItemListener
Java JCheckBox Example: Food Order
Java JRadioButton

 The JRadioButton class is used to create a radio button.


 It is used to choose one option from multiple options.
 It is widely used in exam systems or quiz.
 It should be added in ButtonGroup to select one radio
button only.
Commonly used Constructors in JRadioButton
Commonly used Methods in JRadioButton
Java JRadioButton Example
Java JRadioButton Example with ActionListener
Java JComboBox

 The object of Choice class is used to show popup menu of


choices.
 Choice selected by user is shown on the top of a menu.
 It inherits JComponent class.
Commonly used Constructors in JComboBox
Commonly used Methods in JComboBox
Java JTextField

 The object of a JTextField class is a text component that


allows the editing of a single line text.
 It inherits JTextComponent class.
Commonly used Constructors in JTextField
Commonly used Methods in JTextField
Java JTextField Example
Java JTextField Example with ActionListener
JScrollPane Example
Java JList
 The object of JList class represents a list of text items.
 The list of text items can be set up so that the user can
choose either one item or multiple items.
 It inherits JComponent class.
Commonly used Constructors in JList
Commonly used Methods in JList
Java JList Example
Containers in Java
 A container is a kind of component that holds and manages other
components.
 JComponent objects can be containers, because the JComponent class
descends from the Container class.
 Three of the most useful container types are JFrame , JPanel, and JApplet.
 A JFrame is a top-level window on your display. JFrame is derived from
JWindow, which is pretty much the same but lacks a border.
 A JPanel is a generic container element used to group components inside
of JFrames and other JPanels.
 The JApplet class is a kind of container that provides the foundation for
applets that run inside web browsers.
Containers in Java
 A Container class can be described as a special component that can hold
the gathering of the components.
 There are two types of Swing Containers, they are top-level
containers and low-level containers.
 Top-Level containers are heavyweight containers such
as JFrame, JApplet, JWindow, and JDialog.
 Low-Level containers are lightweight containers such as JPanel.
 The most commonly used containers are JFrame, JPanel and JWindow.
 The important methods of the Container class
are add(), invalidate() and validate().
Example of Container
Layout managers in Java
 The LayoutManagers are used to arrange components in a particular manner.
 The Java LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms.
 LayoutManager is an interface that is implemented by all the classes of layout
managers.
 There are the following classes that represent the layout managers:
 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout
 javax.swing.BoxLayout
 javax.swing.GroupLayout
 javax.swing.ScrollPaneLayout
 javax.swing.SpringLayout etc.
Java BorderLayout
 The BorderLayout is 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 a frame or window. The BorderLayout provides
five constants for each region:
 public static final int NORTH
 public static final int SOUTH
 public static final int EAST
 public static final int WEST
 public static final int CENTER
Constructors of BorderLayout class

 BorderLayout(): creates a border layout but with no gaps


between the components.
 BorderLayout(int hgap, int vgap): creates a border layout
with the given horizontal and vertical gaps between the
components.
Example of BorderLayout class: Using BorderLayout()
constructor
Example of BorderLayout class: Using
BorderLayout(int hgap, int vgap) constructor
Java GridLayout
 The Java GridLayout class is used to arrange the components in a
rectangular grid.
 One component is displayed in each rectangle.
Constructors of GridLayout class
 GridLayout(): creates a grid layout with one column per component in a
row.
 GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
 GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns along with given horizontal and
vertical gaps.
Example of GridLayout class: Using GridLayout()
Constructor
Example of GridLayout class: Using GridLayout(int
rows, int columns) Constructor
Example of GridLayout class: Using GridLayout(int rows, int columns, int
hgap, int vgap) Constructor
Java FlowLayout
 The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow).
 It is the default layout of the applet or panel.

Fields of FlowLayout class


 public static final int LEFT
 public static final int RIGHT
 public static final int CENTER
 public static final int LEADING
 public static final int TRAILING
Constructors of FlowLayout class
 FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
 FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
Example of FlowLayout class: Using FlowLayout()
constructor
Example of FlowLayout class: Using FlowLayout(int align)
constructor
Java CardLayout
 The Java CardLayout class manages the components in such a manner
that only one component is visible at a time.
 It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout Class


 CardLayout(): creates a card layout with zero horizontal and vertical gap.
 CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
Commonly Used Methods of CardLayout Class
 public void next(Container parent): is used to flip to the next card of the
given container.
 public void previous(Container parent): is used to flip to the previous card
of the given container.
 public void first(Container parent): is used to flip to the first card of the
given container.
 public void last(Container parent): is used to flip to the last card of the
given container.
 public void show(Container parent, String name): is used to flip to the
specified card with the given name.
Example of CardLayout Class: Using Default Constructor

 Program
Example of CardLayout Class: Using Parameterized
Constructor
ScrollPaneLayout

 The layout manager is used by JScrollPane. JScrollPaneLayout is


responsible for nine components: a viewport, two scrollbars, a row header,
a column header, and four "corner" components.
 Constructor
 ScrollPaneLayout(): The parameterless constructor is used to create a
new ScrollPanelLayout.
Example of ScrollPaneLayout
ScrollPaneDemo1
Delegation Event Model in Java
 An event can be defined as changing the state of an object or behavior by
performing actions.
 Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
 The Delegation Event model is defined to handle events in GUI programming
languages.
 The GUI stands for Graphical User Interface, where a user graphically/visually
interacts with the system.
 The GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an event
that is mapped to a code to respond to functionality to the user.
 This is known as event handling.
 The java.awt.event package can be used to provide various event classes.
Event Processing in Java
Event Processing in Java
 The modern approach for event processing is based on the Delegation
Model.
 It defines a standard and compatible mechanism to generate and process
events.
 In this model, a source generates an event and forwards it to one or more
listeners.
 The listener waits until it receives an event.
 Once it receives the event, it is processed by the listener and returns it.
 The UI elements are able to delegate the processing of an event to a separate
function.
Event Processing in Java

 Basically, an Event Model is based on the following three


components:

 Events
 Events Sources
 Events Listeners
Events
 The Events are the objects that define state change in a source.
 An event can be generated as a reaction of a user while interacting with GUI
elements.
 Some of the event generation activities are moving the mouse pointer,
clicking on a button, pressing the keyboard key, selecting an item from the
list, and so on.
 We can also consider many other user operations as events.
 The Events may also occur that may be not related to user interaction, such
as a timer expires, counter exceeded, system failures, or a task is completed,
etc.
 We can define events for any of the applied actions.
Classification of Events
Classification of Events
 Foreground Events
 Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI).
 Interactions are nothing but clicking on a button, scrolling the scroll bar,
cursor moments, etc.
 Background Events
 Events that don’t require interactions of users to generate are known as
background events.
 Examples of these events are operating system failures/interrupts,
operation completion, etc.
Event Sources
 In few cases, the event notification will only be sent to listeners that
register to receive them.
 Some listeners allow only one listener to register. Below is an example:
 From the above syntax, the Type is the name of the event, and e2 is the
event listener's reference. When the specified event occurs, it will be
notified to the registered listener. This process is known
as unicasting events.
Event Sources
 A source is an object that causes and generates an event.
 It generates an event when the internal state of the object is changed.
 The sources are allowed to generate several different types of events.
 A source must register a listener to receive notifications for a specific event.
Each event contains its registration method.
 From the above syntax, the Type is the name of the event, and e1 is a reference to
the event listener.For example, for a keyboard event listener, the method will be
called as addKeyListener().
 For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the
respected source, all the events will be notified to registered listeners and
receive the event object. This process is known as event multicasting.
Advantages of Using the Event Delegation Model in Java
 Efficient event handling: The Event Delegation Model avoids the
overhead of sending events to every component in the GUI hierarchy by
delegating the event handling task to the appropriate component. This
makes event handling more efficient and reduces the computational load
on the system.
 Flexibility: The Event Delegation Model allows for dynamic changes in
the GUI hierarchy, as components can be added or removed without
affecting the event handling process. This makes it easy to modify the GUI
without affecting the underlying coding.
 Improved code organization: The Event Delegation Model allows
developers to separate the code that generates events from the code that
handles events. This improves the organization and readability of the
code, making it easier to maintain and modify in the future.
Advantages of Using the Event Delegation Model in Java

 Encapsulation: The Event Delegation Model promotes encapsulation by


keeping the event handling logic within the component that is responsible
for handling the event. This reduces the coupling between components
and promotes modular design.
 Customization: The Event Delegation Model allows developers to
customize the behavior of the event handling process by creating custom
event types and event listeners. This makes it easy to extend the event
handling capabilities of the system.
Implementing the Event Delegation Model in Java
 Implementing the Event Delegation Model in Java involves the following steps:
 Create a custom event class: The first step is to create a custom event class
that extends the java.awt.AWTEvent class. This class should contain any
necessary data for the event.
 Create a custom event listener interface: The next step is to create a custom
event listener interface that extends the java.util.EventListener interface. This
interface should define methods for handling the custom event.
 Register the event listener: The next step is to register the event listener with
the component that generates the event. This is typically done using the
addEventListener() method.
 Implement the event handling logic: The final step is to implement the event
handling logic in the custom event listener. This typically involves casting the
event object to the custom event class and extracting any necessary data. The
event listener should then perform the appropriate actions based on the event.
Design Goals of Event Delegation Model in Java
 The design goals of the event delegation model are as following:
 It is easy to learn and implement
 It supports a clean separation between application and GUI code.
 It provides robust event handling program code which is less error-prone
(strong compile-time checking)
 It is Flexible, can enable different types of application models for event
flow and propagation.
 It enables run-time discovery of both the component-generated events as
well as observable events.
 It provides support for the backward binary compatibility with the
previous model.
Event and Listener (Java Event Handling)

 Changing the state of an object is known as an event.


 For example, click on button, dragging mouse etc.
 The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Event and Listener (Java Event Handling)
Java Event Handling Code

We can put the event handling code into one of the following places:
 Within class
 Other class
 Anonymous class
Java event handling by implementing ActionListener
Java event handling by outer class
Java Adapter Classes
 Java adapter classes provide the default implementation of
listener interfaces.
 If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.
 The adapter classes are found in java.awt.event,
java.awt.dnd and javax.swing.event packages.
Pros of using Adapter classes

 It assists the unrelated classes to work combined.


 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.
java.awt.event Adapter classes
java.awt.dnd Adapter classes
javax.swing.event Adapter classes
Java MouseAdapter Example
Java MouseMotionAdapter Example
Java KeyAdapter Example
JDBC
 JDBC stands for Java Database Connectivity. JDBC is a Java API to connect
and execute the query with the database.
 It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers
to connect with the database.
 We can use JDBC API to access tabular data stored in any relational
database.
 By the help of JDBC API, we can save, update, delete and fetch data from
the database.
 The java.sql package contains classes and interfaces for JDBC API.
JDBC
Why Should We Use JDBC
 Before JDBC, ODBC API was the database API to connect and execute the
query with the database.
 But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured).
 That is why Java has defined its own API (JDBC API) that uses JDBC
drivers (written in Java language).
 We can use JDBC API to handle database using Java program and can
perform the following activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.
JDBC Components
 JDBC has four major components that are used for the interaction with
the database.

 JDBC API: JDBC API provides various interfaces and methods to establish
easy connection with different databases.
 JDBC Test Suite: JDBC Test suite facilitates the programmer to test the
various operations such as deletion, updation, insertion that are being
executed by the JDBC Drivers.
JDBC Components
 JDBC Driver Manger: JDBC Driver manager loads the database-specific
driver into an application in order to establish the connection with the
database.
 The JDBC Driver manager is also used to make the database-specific call
to the database in order to do the processing of a user request.
 JDBC ODBC Bridge Driver: JDBC-ODBC Bridge Drivers are used to
connect the database drivers to the database.
 The bridge does the translation of the JDBC method calls into the ODBC
method call. It makes the usage of the sun.jdbc.odbc package that
encompasses the native library in order to access the ODBC (Open
Database Connectivity) characteristics.
Architecture of JDBC
 Application: It is the Java servlet or an applet that communicates with the data source.
 The JDBC API: It allows the Java programs to perform the execution of the SQL
statements and then get the results.
 A few of the crucial interfaces and classes defined in the JDBC API are the following:
 Drivers
 DriverManager
 Statement
 Connection
 CallableStatement
 PreparedStatement
 ResultSet
 SQL data
DriverManager: DriverManager plays a crucial role in the architecture of JDBC.
 It uses database-specific drivers to connect the enterprise applications to various
databases.
JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC
driver which conveniently interacts with the respective data source.
Components of JDBC
Different Types of Architecture of JDBC
 The architecture of the JDBC consists of two and three tiers model in
order to access the given database.
 Two-tier model: In this model, the application interacts directly with the
source of data. The JDBC driver establishes the interaction between the
data source and the application. When a query is sent by the user to the
data source, the reply of those sent queries is sent directly to the user.
 The source of data can be located on a different machine, and that
machine is connected to the user machine following a client-server
paradigm, where the machine which is sending the query is the client
machine, and the machine that is sending the result of those queries is
acting as the server.
Different Types of Architecture of JDBC

 Three-tier model: In this model, the queries of the user are being sent to
the middle-tier services, from where the commands are sent again to the
source of data.
 The answers to those queries are reverted to the middle tier, and from
there, it is again sent to the user.
JDBC Driver

 JDBC Driver is a software component that enables java application to


interact with the database.
 There are 4 types of JDBC drivers:
 JDBC-ODBC bridge driver
 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)
JDBC-ODBC bridge driver

 The JDBC-ODBC bridge


driver uses ODBC driver
to connect to the
database. The JDBC-
ODBC bridge driver
converts JDBC method
calls into the ODBC
function calls. This is
now discouraged
because of thin driver.
JDBC-ODBC bridge driver
Advantages: Disadvantages:

 easy to use.  Performance degraded because JDBC


 can be easily connected to any database. method call is converted into the ODBC
function calls.
 The ODBC driver needs to be installed
on the client machine.
Native-API driver

 The Native API


driver uses the
client-side libraries
of the database.
The driver converts
JDBC method calls
into native calls of
the database API.
It is not written
entirely in java.
Native-API driver
Advantage: Disadvantage:

 performance upgraded than  The Native driver needs to be


JDBC-ODBC bridge driver. installed on the each client
machine.
 The Vendor client library needs
to be installed on client
machine.
Network Protocol driver

 The Network Protocol


driver uses middleware
(application server) that
converts JDBC calls
directly or indirectly
into the vendor-specific
database protocol. It is
fully written in java.
Network Protocol driver
Advantage: Disadvantages:

 No client side library is required  Network support is required on client


because of application server machine.
that can perform many tasks  Requires database-specific coding to
be done in the middle tier.
like auditing, load balancing,
logging etc.  Maintenance of Network Protocol
driver becomes costly because it
requires database-specific coding to
be done in the middle tier.
Thin driver

 The thin driver converts


JDBC calls directly into
the vendor-specific
database protocol. That
is why it is known as
thin driver. It is fully
written in Java language
Thin driver
Advantage: Disadvantage:

 Better performance than all other  Drivers depend on the Database.


drivers.
 No software is required at client side or
server side.
Java Database Connectivity with 5 Steps

 There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close connection
Java Database Connectivity with 5 Steps
Register the driver class

 The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
Create the connection object

 The getConnection()
method of
DriverManager class is
used to establish
connection with the
database.
Create the Statement object

 The createStatement()
method of Connection
interface is used to
create statement. The
object of statement is
responsible to execute
queries with the
database.
Execute the query

 The executeQuery()
method of Statement
interface is used to
execute queries to the
database. This method
returns the object of
ResultSet that can be
used to get all the
records of a table.
Close the connection object

 By closing connection
object statement and
ResultSet will be closed
automatically. The
close() method of
Connection interface is
used to close the
connection.
Java Database Connectivity with MySQL
 In this example we are using MySql as the database. So we need to know
following informations for the mysql database:
 Driver class: The driver class for the mysql database
is com.mysql.jdbc.Driver.
 Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/test where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may
also use IP address, 3306 is the port number and test is the database name.
We may use any database, in such case, we need to replace the test with
our database name.
 Username: The default username for the mysql database is root.
 Password: It is the password given by the user at the time of installing the
mysql database. In this example, we are going to use root as the password.
Example to Connect Java Application with mysql database
Example to Connect Java Application with mysql database
with User Input
Example to update data in mysql database
with User Input
Example to Delete data in mysql database
Example to Delete data in mysql database
with User Input

You might also like