You are on page 1of 120

JAVA PROGRAMMING BY

D R . R . R A M A L A KS H M I
D R . K . M U R U G E S WA R I
M R . M . K . N AG A R A J A N
M R S . A . M .G U R U S I G A A M A N I

© Kalasalingam academy of research and education


Course Outline

Course description
CO 1.Understand the objet oriented concepts using java Java still has its importance and popularity in the
software industry, in spite of recent development of
several high level languages. It has an excellent support
CO2 Apply fundamental programming concepts of Java of high-level as well as low-level functionality, which
to develop stand alone applications makes it suitable for many applications. This course
provides students with a comprehensive study of the
Java programming language. Instead of Classroom
CO 3. Solve Real World Problem through reusable and lectures, practical classes stress the strengths of Java,
error free code. which provide the students with the means of writing
efficient, maintainable, and portable code. A course
with mini project is one of the great learning
CO 4. Design and develop distributed applications. opportunities to develop students in various aspects.
This course will also help the students during their
placement sittings, as most of the companies test
CO 5. Implement window based applications using proficiency in programming using Java.
event handling mechanisms

© Kalasalingam academy of research and education 2


Syllabus

UNIT I OOP IN JAVA & INHERITANCE

Object Oriented Programming Concepts - OOP in Java – Characteristics of Java –


Fundamental Programming Structures in Java – Defining classes in Java –
Comments, Data Types, Variables, Operators, Control Flow, Arrays - constructors,
methods -access specifiers - static members – Packages- Inheritance – Super
classes- sub classes –Protected members – constructors in sub classes- Strings.

UNIT II EXCEPTION HANDLING AND I/O

Exceptions - exception hierarchy - throwing and catching exceptions – built-in


exceptions, creating own exceptions, Stack Trace Elements-Input / Output Basics

Unit 1
– Streams – Byte streams and Character streams – Reading and Writing Console
– Reading and Writing Files - abstract classes and methods - final methods and
classes

UNIT III INTERFACES AND MULTITHREADING

Interfaces – defining an interface, implementing interface, differences between


classes and interfaces - extending interfaces - Object cloning -inner classes-
Differences between multi-threading and multitasking, thread life cycle, creating
Outcomes
threads, synchronizing threads, Inter-thread communication, daemon threads -
Generic Programming. • Define Networking basics
UNIT IV AWT AND EVENT DRIVEN PROGRAMMING
• Understand about Networking Classes and Interfaces.
AWT Event Hierarchy- Components - Graphics programming – Applets-Frame –
working with 2D shapes - Using color, fonts, and images - Basics of event • Run stand alone applications using Client-Server Programming
handling - event handlers - adapter classes - actions - mouse events -
Introduction to Swing – layout management - Swing Components – Windows –
Menus – Dialog Boxes. • Know about datagrams.
UNIT V NETWORKING AND JDBC • JDBC Connectivity and its Components
Networking Basics - The Networking Classes and Interfaces -TCP/IP Client Sockets
URL TCP/IP Server Sockets – Datagrams - A Relational Database Overview - JDBC
• Example Casestudies.
Introduction - JDBC Product Components - JDBC Architecture - Case studies.

© Kalasalingam academy of research and education 3


Unit 5 Outline

Lesson 1. Networking Basics


In this unit, students will learn about
Networking basics, Client and server Sockets,
Lesson 2. Client-Server Programming and Database, how to work with JDBC and its
components.
Lesson 3.Relational Database

Lesson 4. JDBC

Lesson 5. Case Studies

© Kalasalingam academy of research and education 4


Course Progress (use before starting new lesson)
Lesson 1. Networking Basics

Lesson 2. Client-Server Programming

Lesson 3. Relational Database

Lesson 4. JDBC

Lesson 5. Case Studies

© Kalasalingam academy of research and education 5


What is Networking?
When two processes, lying on same or different machines are communicating over the network
is called networking.

© Kalasalingam academy of research and education 6


Server & Client

© Kalasalingam academy of research and education 7


Elements of Client-Server Computing

© Kalasalingam academy of research and education 8


Single machine-multiple clients

© Kalasalingam academy of research and education 9


Client is a process
One interaction may run numerous customers (measures) at a time.
Customer isn't a machine, it is an interaction.

- >Browser opens google.com is a customer.

- >Yahoo courier associated with a visit worker is a customer.


- > CuteFTP transferring a record to FTP Server is a Client.
All previously mentioned customers( CuteFTP, Messenger, Browser) run together on a Single
Machine Concurrently.

© Kalasalingam academy of research and education 10


Server is a Process

One machine may run various servers(processors) at a time.

Worker isn't a machine, it is an interaction.

Tomcat web worker is a cycle.

WAMP PHP worker is a cycle.

Filezilla FTP worker is a cycle.

All the previously mentioned workers run together on a solitary machine simultaneously.

© Kalasalingam academy of research and education 11


Single machine Multiple Servers

© Kalasalingam academy of research and education 12


Server & Client
Since Operating Systems can execute numerous cycles simultaneously utilizing preemptive
booking.

Subsequently, one machine may run Multiple workers and Clients together.

Customer and worker measures convey over the organization to trade information in type of
solicitation and reaction.

© Kalasalingam academy of research and education 13


How Clients and Servers are identified?

Clients and Servers are extraordinarily distinguished on a solitary machine by remarkable Port
Numbers.
Extraordinary Port Number is appointed by OS.
Interaction can ask wanted port number from OS, or OS will allocate next accessible port
number to a cycle.
Port number is a two bytes unsigned number going from 0-65535.

© Kalasalingam academy of research and education 14


Ports

© Kalasalingam academy of research and education 15


Communication Rules(Protocols)

© Kalasalingam academy of research and education 16


Protocol over Phone

At the point when you bring somebody over telephone and start discussion, you follow
convention.
First you welcome and say "Hi", then, at that point you tell your name "I'm Vijay", then, at that
point you ask with whom you need to talk "May I converse with Tisha?".
In like manner when discussion is over you say "Bye" and other would react "Have a Good Day".

This is Protocol

© Kalasalingam academy of research and education 17


Protocol Responsibilities

Applies a bunch of Rules.


Converts your application information into byte stream and viceversa.
Breaks information into packets and send over network.
Gets affirmations of sent packets.
Chooses network course to send information packets.

© Kalasalingam academy of research and education 18


Protocol Stack
A gathering of organization conventions that cooperate to send and accept your information
over the organization, is known as a Protocol Stack.
The TCP/IP convention utilizes four layers that guide to the OSI model:

© Kalasalingam academy of research and education 19


Protocol Stack Communication

© Kalasalingam academy of research and education 20


TCP/IP Protocol Stack

Applications Layer:
Contains client custom and undeniable level application conventions like HTTP,FTP,SMTP, Telnet
and so on
Transport Layer:
Contains TCP or UDP conventions, liable for making information bundles and send or get across
Network.
Your custom application will impart to this layer.
Network Layer:
Contains IP convention that utilizations steering data to choose course of information bundle to
send it to the objective.
Link Layer :
Converts information into signals.

© Kalasalingam academy of research and education 21


TCP Protocols

TCP(Transport Control Protocol) is an association situated convention that gives a solid


progression of information between two PCs.

© Kalasalingam academy of research and education 22


UDP Protocols

UDP(User Datagram Protocol):It is a show that sends self-ruling heaps of data(called datagrams)
beginning with one PC then onto the following with NO confirmation about appearance.

Example applications:
Clock server
Ping

© Kalasalingam academy of research and education 23


What is a Socket?

socket is an association between two hosts. It can perform seven essential tasks:
Associate with a distant machine
Send information
Get information
Close an association
Tie to a port
Tune in for approaching information
Acknowledge associations from far off machines on the bound port

© Kalasalingam academy of research and education 24


Sockets
Server and Client have network end focuses called Sockets. Its are bound to a particular port.

© Kalasalingam academy of research and education 25


Java Socket Classes

© Kalasalingam academy of research and education 26


Make TCP Connection

© Kalasalingam academy of research and education 27


Make UDP connection

© Kalasalingam academy of research and education 28


Networking with JAVA-Introduction

Java's organizing support is the idea of an attachment. An attachment distinguishes an endpoint


in an organization.
Attachment correspondence happens by means of a convention. Web Protocol(IP) is a low-level
controlling show that breaks data into little packages and sends them to an area across an
association, which doesn't guarantee to pass on said bundles to the goal.
Transmission Control Protocol(TCP) is a more critical level show that sorts out some way to
effectively string together these bundles, organizing and retransmitting them as imperative to
constantly send data.
A third show, User Datagram Protocol(UDP) sits directly on TOP of the base IP. At the point when
everything is said in done, UDP executes a really "lightweight" layer over the Internet Protocol.

© Kalasalingam academy of research and education 29


Networking with JAVA

When an association has been set up, a more significant level convention guarantees, which is
subject to which port you are utilizing.
TCP/IP saves the lower 1024 ports for explicit conventions. A large number of these will appear
to be recognizable to you on the off chance that you have invested any energy riding the
Internet.
Port number 21 is for FTP; 23 is for TELNET; 25 is for email; 80 is for HTTP; 110 is for netnews
and some more.
It is dependent upon every convention to decide how a customer ought to collaborate with the
port.

© Kalasalingam academy of research and education 30


Networking in Java

The classes contained in the java.net package are


Socket
ServerSocket
SocketAddress
InetAddress
InetSocketAddress
URL
DatagramPacket
DatagramSocket
URLClassLoader
URLConnection
HttpURLConnection

© Kalasalingam academy of research and education 31


The Networking Classes and Interfaces
Java maintains TCP/IP both by growing the for the most part settled stream I/O interface.
Java maintains both the TCP and UDP show families. TCP is used for trustworthy stream-based
I/O across the association. UDP maintains a simpler, hereafter faster, feature point datagram-
orchestrated model. The classes contained in the java.net pack are showed up here:

© Kalasalingam academy of research and education 32


Classes contained in the java.net package

© Kalasalingam academy of research and education 33


InetAddress Class
The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address. You interact with this class by using the name of an IP host, which is
more convenient and understandable than its IP address.
The InetAddress class has no visible constructors. To create an InetAddress object, you have to
use one of the available factory methods. Factory methods are merely a convention whereby
static methods in a class return an instance of that class.
Three commonly used InetAddress factory methods are shown here:
Static InetAddress getLocalHost() throws UnknownHostException
Static InetAddress getByName(string hostName) throws UnknownHostException
Static InetAddress[] getAllByName(String hostName) throws UnknownHostException
The getLocalHost() method simply returns the InetAddress object that represents the local host.
The getByName() method returns an InetAddress for a host name passed to it. If these methods
are unable to resolve the host name, they throw an UnknownHostException.

© Kalasalingam academy of research and education 34


InetAddress

© Kalasalingam academy of research and education 35


TCP/IP Sockets in Java
The ServerSocket class is intended to be a \listener," which trusts that customers will interface prior to busy. In this
manner, ServerSocket is for workers.
The Socket class is for customers. It is intended to interface with worker attachments and start convention trades.
two constructors used to make customer attachments:

Socket(String hostName, int port) tosses UnknownHostException,IOException

Socket(InetAddress ipAddress, int port) tosses IOException

Techniques
InetAddress getInetAddress( ) - Returns the InetAddress related with the Socket object. It returns invalid if the
attachment isn't associated.
int getPort( ) - Returns the far off port to which the conjuring Socket object is associated. It returns 0 if the attachment
isn't associated.
int getLocalPort( ) - Returns the neighborhood port to which the summoning Socket object is bound. It returns {1 if the
attachment isn't bound.

© Kalasalingam academy of research and education 36


Listing 2:Using Socket Class

© Kalasalingam academy of research and education 37


TCP/IP Client Sockets
The creation of a Socket object implicitly establishes a connection between the client and server.
Here are two constructors used to create

© Kalasalingam academy of research and education 38


TCP/IP Client Sockets
Socket defines several instance methods. For example, a Socket can be examined at any time for
the address and port information associated with it. Some of the methods are:

© Kalasalingam academy of research and education 39


TCP/IP Client sockets
You can gain access to the input and output streams associated with a Socket by use of the
getInputStream() and getOutputStream() methods, as shown here

© Kalasalingam academy of research and education 40


Socket Based Client Server Programming
The two key classes from the java.net bundle utilized in making of worker and customer
programs are: Server Socket and Socket

A worker program makes a specic sort of attachment that is utilized to tune in for customer
demands (Server Socket), For the situation of an association demand, the program makes
another Socket through which it will trade information with the customer utilizing input and
output streams.

© Kalasalingam academy of research and education 41


Creating a Server Program
Open the Server Socket:
ServerSocket worker = new ServerSocket( PORT );
Wait for the Client Request:
Attachment customer = server.accept();
Make I/O streams for imparting to the customer
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
Perform communication with client
Get from customer: String line = is.readLine();
Ship off customer: os.writeBytes(\Hello");
Close socket:
client.close();

.
© Kalasalingam academy of research and education 42
Creating Client Program

Create a Socket Object:


Socket customer = new Socket(server, port id);
Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
Perform I/O or communication with the server:
Get information from the worker: String line = is.readLine();
Send information to the worker: os.writeBytes(\Hello");
Close the socket when done:
client.close();

© Kalasalingam academy of research and education 43


Listing 3:TCP/IP Server Program & TCP/IP Client
Program

© Kalasalingam academy of research and education 44


Output

© Kalasalingam academy of research and education 45


URL Class

The URL gives a sensibly intellible structure to extraordinarily distinguish or address data on the
Internet.
URLs are omnipresent; each program utilizes them to recognize data on the Web.
Inside Java's organization class library, the URL class gives a basic, brief API to get to data across
the Internet utilizing URLs.
Java's URL class has a few constructors; each can toss a MalformedURLException.
One ordinarily utilized structure indicates the URL with a string that is indistinguishable from
what you see showed in a program.

. 46
© Kalasalingam academy of research and education
URL Class

The following two types of the constructor permit you to separation the URL into its segment
parts:
URL(String protocolName, String hostName, int port, String way) tosses MalformedURLException

URL(String protocolName, String hostName, String way) tosses MalformedURLException

© Kalasalingam academy of research and education 47


URL Connection

URL Connection is a broadly useful class for getting to the qualities of a distant asset.
When you make an association with a distant worker, you can utilize URL Connection to review
the properties of the far off object before really shipping it locally. These ascribes are uncovered
by the HTTP convention particular.

© Kalasalingam academy of research and education 48


Topic 1
Introduction of Client & Server

Topic 2
Protocol stack

Topic 3
TCP/IP & UDP Protocols

Topic 4
Working with Java

Topic 5

The networking classes and Interfaces


First Lesson Summary
Learned about Client & Server, Protocol Stack, TCP/IP & UDP
Protocols, Working with Java and networking classes and
Interfaces

© Kalasalingam academy of research and education 49


Course Progress (use before starting new lesson)
Lesson 1. Networking Basics

Lesson 2. Client-Server Programming

Lesson 3. Relational Database

Lesson 4. JDBC

Lesson 5. Case Studies

© Kalasalingam academy of research and education 50


TCP/IP Server Sockets
Java has an alternate attachment class that should be utilized for making worker applications.
The ServerSocket class is utilized to make workers that tune in for one or the other
neighborhood or far off customer projects to associate with them on distributed ports.
ServerSockets are very not quite the same as would be expected attachments. At the point
when you make a ServerSocket, it will enlist itself with the framework as having an interest in
customer associations.
The Constructors for ServerSocket mirror the port

© Kalasalingam academy of research and education 51


Create TCP Server

Class ServerSocket makes a TCP worker and hangs tight for Client demand.
ServerSocket ss=new ServerSocket(4444);
socket client=ss.accept();
server will undoubtedly port number 4444.
server is hanging tight for customer demand by calling technique ss.accept().

© Kalasalingam academy of research and education 52


Create TCP Client

Class Socket makes a TCP Client.

server IP and Port number are passes to Socket parametrized constructor.

socket client=new Socket("127.0.0.1", 4444);

Made socket occasion will build up association with server.

© Kalasalingam academy of research and education 53


Java Sockets

© Kalasalingam academy of research and education 54


Sockets IO

Sockets give an interface to programming networks at the vehicle layer.


Organization correspondence utilizing Sockets is particularly like performing record I/O
The streams utilized in record I/O activity are additionally material to socket based I/O.
socket based correspondence is customizing language autonomous.
That implies, an attachment program written in Java language can likewise impart to a program
written in Java or non-Java attachment program.

© Kalasalingam academy of research and education 55


Read and Write from Socket
I/O classes are used to read and write byte streams from the socket.
Socket s=new Socket(“127.0.0.1”,4444);//Client side
Or
Socket s=ss.accept(); //Server Side
DataOutputStream os;
DataInputStream is;
is=new DataInputStream(s.getInputStream());
os=new DataOutputStream(s.getOutputStream());
String line=is.readLine();
os.writeBytes(“Hello\n”);

© Kalasalingam academy of research and education 56


Network Communication

Image src :community.rti.com

© Kalasalingam academy of research and education 57


Client and Server Communication
1:ServerSocket server=new ServerSocket(1234); 3:Socket client=new socket(“localhost”,1234);
2: Socket client=server.accept(); 4: in=new DataInputStream(client.getInputStream())
4: in=new DataInputStream(client.getInputStream()) 5: out= new
5: out= new DataOutputStream(client.getOutputStream())
DataOutputStream(client.getOutputStream()) 6: out.writeBytes(“Hello Server\n”)
7: String line=in.readLine(); 9:String line=in.readLine();
8:out.writeBytes(“Hello client\n”) 10.client.close()
10:client.close()

© Kalasalingam academy of research and education 58


Echo Client and Server
Echo Server echoes the content sent by Client
Utilizations TCP Protocol
server will deal with various customers Sequentially
server will end correspondence when Client sends "Bye".

© Kalasalingam academy of research and education 59


Echo Server

© Kalasalingam academy of research and education 60


Echo Client

© Kalasalingam academy of research and education 61


Output

© Kalasalingam academy of research and education 62


Multi-threaded Echo Server

- Handles numerous Clients simultaneously


- Application functions as a server tuning in for demands from customer on indicated port.
- Every single association is treat as another string.
- Once the association is bound the customer can communicate something specific and finds a
solution back as a reverberation.

© Kalasalingam academy of research and education 63


Multithreaded Echo Client

© Kalasalingam academy of research and education 64


Multithreaded Echo Server

© Kalasalingam academy of research and education 65


Multi-Threaded Echo Client & Server -Output

© Kalasalingam academy of research and education 66


UDP Communication

© Kalasalingam academy of research and education 67


Quote Server

- Quote UDP Server


- Receives void bundle from Client
- Replies to the Client with an irregular statement of the day

© Kalasalingam academy of research and education 68


Read text from URL

© Kalasalingam academy of research and education 69


Java.net.URL
Interesting Methods
getProtocol-Returns the convention identifier segment of the URL.
getAuthority-Returns the position part of the URL.
getHost-Returns the host name segment of the URL.
getPort-Returns the port number part of the URL. The getPort technique returns a whole
number that is the port number. On the off chance that the port isn't set, getPort returns - 1.
getPath-Returns the way part of this URL.
getQuery-Retuns the question part of this URL.
getFile-Returns the filename segment of the URL. The getFile strategy returns equivalent to
getPath, in addition to the connection of the worth of getQuery, assuming any.

© Kalasalingam academy of research and education 70


Datagrams

TCP/IP organizing gives a serialized, unsurprising, solid stream of parcel information.


Datagrams are heaps of data passed between machines
Once the datagram has been delivered to its expected objective, there is no confirmation that it
will show up or even that somebody will be there to get it.
Java executes datagrams on top of the UDP convention by utilizing two classes:
The Datagram Packet object is the information compartment, while the Datagram Socket is the
system used to send or get the Datagram Packets.

.
© Kalasalingam academy of research and education 71
DatagramSocket

DatagramSocket characterizes four public constructors. They are displayed here:


DatagramSocket() tosses SocketException
DatagramSocket(int port) tosses SocketException
DatagramSocket(int port, InetAddress ipAddress) tosses SocketException
DatagramSocket(SocketAddress address) tosses SocketException

© Kalasalingam academy of research and education 72


DatagramSocket

The first makes a Datagram Socket bound to any unused port on the nearby PC.
The second makes a Datagram Socket bound to the port indicated by port.
The third develops a Datagram Socket bound to the predetermined port and Inet Address.
The fourth develops a Datagram Socket bound to the predetermined Socket Address.

© Kalasalingam academy of research and education 73


DatagramSocket

DatagramSocket characterizes Two most significant strategies are send() and get() , which are
displayed here:
void send(DatagramPacket bundle) tosses IOException
void receive(DatagramPacket bundle) tosses IOException
The send() strategy sends bundle to the port indicated by parcel.
The get() strategy trusts that a bundle will be gotten from the port indicated by parcel and
returns the outcome.

© Kalasalingam academy of research and education 74


DatagramPacket

DatagramPacket characterizes a few constructors. Four are displayed here:


DatagramPacket(byte data[], int size)
DatagramPacket(byte data[], int counterbalance, int size)
DatagramPacket(byte data[], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data[], int counterbalance, int size, InetAddress ipAddress, int port)

© Kalasalingam academy of research and education 75


DatagramPacket

The main constructor indicates a support that will get information and the size of a bundle. It is
utilized for getting information over a DatagramSocket.
The subsequent structure permits you to determine a balance into the cradle at which
information will be put away.
The third structure indicates an objective location and port , which are utilized by a
DatagramSocket to figure out where the information in the parcel will be sent.
The fourth structure sends parcels starting at the predetermined balance into the information.

© Kalasalingam academy of research and education 76


DatagramPacket
DatagramPacket characterizes a few techniques, that offer admittance to the location and port
number of a bundle, just as the crude information and its length.
By and large, the get strategies are utilized on bundles that are gotten and the set techniques
are utilized on parcels that will be sent.

© Kalasalingam academy of research and education 77


UDP Datagrams
Difference between TCP and UDP
UDP works a piece dierently from TCP. At the point when you send information through TCP you
initially make an association. When the TCP association is set up TCP guarantess that your
information shows up at the opposite end, or it will reveal to you that a blunder happened.

With UDP you simply send parcels of information (datagrams) to some IP address on the
organization. You have no assurance that the information will show up. You likewise have no
assurance about the request which UDP bundles show up in at the recipient. This implies that
UDP has less convention overhead (no stream honesty checking) than TCP.

UDP is fitting for information moves where it doesn't make any difference if a parcel is lost on
the move. For example, envision an exchange of a live TV-signal over the web.

© Kalasalingam academy of research and education 78


Sending and Receiving Data via a DatagramSocket

To send information by means of Java's DatagramSocket you should initially make a


DatagramPacket.
byte[] cradle = new byte[65508];
InetAddress address = InetAddress.getByName("jenkov.com");
DatagramPacket parcel = new DatagramPacket(buffer, buffer.length, address, 9000);

The byte support (the byte exhibit) is the information that will be sent in the UDP datagram. The
length of the above support, 65508 bytes, is the greatest measure of information you can send
in a solitary UDP bundle. The length given to the DatagramPacket constructor is the length of the
information in the cradle to send. All information in the support after that measure of
information is disregarded.

.
© Kalasalingam academy of research and education 79
Sending and Receiving Data via a
DatagramSocket(Cond..)

To send the DatagramPacket you should make a DatagramSocket focused on at sending


information.
datagramSocket = new DatagramSocket();
To send information you call the send() strategy, similar to this:
datagramSocket.send(packet);
Getting information through a DatagramSocket is finished by first making a DatagramPacket and
afterward getting information into it by means of the DatagramSocket's get() technique.
. DatagramSocket datagramSocket = new DatagramSocket(80);
byte[] buffer = new byte[10];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);

© Kalasalingam academy of research and education 80


Listing 5:DReceiver

© Kalasalingam academy of research and education 81


DSender

© Kalasalingam academy of research and education 82


Output

© Kalasalingam academy of research and education 83


Listing 6:UDPServer

© Kalasalingam academy of research and education 84


Listing 8:UDPClient

© Kalasalingam academy of research and education 85


Output

© Kalasalingam academy of research and education 86


Topic 1
Creation of TCP Server & Client

Topic 2
Sockets

Topic 3
Creation of UDP Server & Client

Topic 4

Echo Server

Topic 5

Second Lesson Summary


Learned about TCP, UDP Client & Server Communication
& Programming, Sockets ,Datagrams

© Kalasalingam academy of research and education 87


Course Progress (use before starting new lesson)
Lesson 1. Networking Basics

Lesson 2. Client-Server Programming

Lesson 3. Relational Database

Lesson 4. JDBC

Lesson 5. Case Studies

© Kalasalingam academy of research and education 88


Database

A data set is a coordinated assortment of data.The information is ordinarily coordinated to show


significant parts of reality(for model, the accessibility of rooms in lodgings), such that supports
measures requiring this information(for model, discovering an inn with opportunities).
Information base framework comprises of
- User
- Data
- Hardware->Where information lives
- Software->Database Management System(DBMS),Control stockpiling and recovery

.
© Kalasalingam academy of research and education 89
Database

The advantage of database


Lessen repetition
Keep away from irregularity
Offer information
Uphold norms
Security limitations
Information respectability
Equilibrium clashing necessity

© Kalasalingam academy of research and education 90


Database

Non-data set frameworks


- Each application has its own records
Repetitive
Need brought together control

© Kalasalingam academy of research and education 91


Database

Data independence
Applications not dependant on how information put away or got to.
Applications can have various perspectives on information
Change stockpiling/recovery methodology without evolving applications.
Data dependency
Change away or recovery procedure powers program change. .

© Kalasalingam academy of research and education 92


Database

Database language
-Host languages
◦ Used to get to information base
◦ Can utilize significant level dialects Java,C,C++,Visual Basic, COBOL,PL/I, Pascal
-Database sublanguage(DSL)
◦ Indicates of data set articles and activities
◦ Blend of Data definition language(DDL) and Data Manipulation
Language(DML)

© Kalasalingam academy of research and education 93


SQL Tables

Table is an assortment of information, coordinated as far as lines and segments .


In DBMS terms, table is referred to as connection and line as tuple.
Table is the basic type of information stockpiling.
A table is additionally considered as a helpful portrayal of relations,

© Kalasalingam academy of research and education 94


Example: Table employee

EMP_NAME ADDRESS SALARY


Ahsduibf DELHI 150000
Jshcybdfjsd MUMBAI 180000
Sgdyuabdakj CHENNAI 200000

In the above table, “Employee” is the table name, “EMP_NAME”, “ADDRESS” and “SALARY” are
the column names. The combination of data of multiple columns forms a row e.g “Ahsduibf”,
“DELHI”, and “150000”.

© Kalasalingam academy of research and education 95


Distributed Database

A distributed information base is a data set in which stockpiling gadgets are not all appended to
a typical handling unit like the CPU, constrained by a circulated data set administration
framework. It very well might be put away in numerous PCs, situated in a similar actual area; or
might be scattered over an organization of interconnected PCs.

© Kalasalingam academy of research and education 96


Distributed database
Advantages:
-Neighborhood independence or site self-sufficiency
A division can handle the information about them(as they are the ones acquainted with it.
- Protection of important information
on the off chance that there were ever a calamitous occasion like fire, the entirety of the information would not be in
one spot, however disseminated in numerous areas
- Modularity
Frameworks can be changed, added and taken out from the conveyed data set without influencing different modules
- Continuous activity
regardless of whether a few hubs go disconnected (contingent upon configuration, similar to reinforcement)

© Kalasalingam academy of research and education 97


Distributed database

Cons
-Intricacy
- Economics
- Security
- Difficult to look after trustworthiness

© Kalasalingam academy of research and education 98


Relational Database

A relational database is a data set that has an assortment of tables of information things, which
is all officially depicted and coordinated by the social model.
Created tables
- Rows called records(tuples)
- Columns are fields(attributes)
First field typically essential key
- Unique for each record
- Primary key can be more than one field.
- Cannot permit invalid qualities

© Kalasalingam academy of research and education 99


Relational Database

Advantages of relational database


-Tables simple to utilize, comprehend and carry out
- Projection and join activities simple to execute.
- Easy to adjust
- Great clearness and deceivability

© Kalasalingam academy of research and education 100


Topic 1
Database

Topic 2
SQL Tables

Topic 3
Distributed Database

Topic 4
Relational Database

Third Lesson Summary


Learned about Database, SQL Tables, Distributed
Database and Relational Database

© Kalasalingam academy of research and education 101


Course Progress (use before starting new lesson)
Lesson 1. Networking Basics

Lesson 2. Client-Server Programming

Lesson 3. Relational Database

Lesson 4. JDBC

Lesson 5. Case Studies

© Kalasalingam academy of research and education 102


Java Database Connectivity(JDBC)

Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to


associate Java application with Database.
JDBC is utilized to associate with different kind of Database like Oracle, MS Access, MYSQL, and
SQL Server.
JDBC can likewise be characterized as the stage free interface between a social information base
and Java Programming.
It permits java program to execute SQL articulation and recover result from data set.

© Kalasalingam academy of research and education 103


Structure of Java Database Connectivity(JDBC)

© Kalasalingam academy of research and education 104


JDBC Driver

JDBC Driver is required to process SQL requests and generate result.


The following are the different types of driver available in JDBC.
Type-1 Driver or JDBC-ODBC bridge
Type-2 Driver or Native API Partly Java Driver
Type-3 Driver or Network Protocol Driver
Type-4 Driver or Thin Driver

© Kalasalingam academy of research and education 105


JDBC-ODBC bridge
Type-1 Driver go about as an extension among JDBC and other information base availability
mechanism(ODBC).
This driver changes over JDBC calls into ODBC calls and diverts the solicitation to the ODBC
driver.

© Kalasalingam academy of research and education 106


JDBC-ODBC Driver

Benefit
Simple to utilize
Permit simple availability to all information base upheld by the ODBC Driver.
Hindrance
Moderate execution time
Reliant upon ODBC Driver.
Utilizations Java Native Interface(JNI)

.
© Kalasalingam academy of research and education 107
JDBC 4.0 API

java.sql
javax.sql
java.sql bundle - This bundle incorporate classes and interface to perform practically all JDBC
activity, for example, making and executing SQL Queries.
java.sql.Connection - makes an association with specic data set
java.sql.CallableStatement - Execute put away methods
java.sql.Driver - make an occurrence of a driver with the DriverManager.
java.sql.DriverManager - This class oversees data set drivers.
java.sql.PreparedStatement - Used to make and execute defined question.
java.sql.ResultSet - It is an interface that give techniques to get to the outcome column by-line.
java.sql.Statement - This interface is utilized to execute SQL explanations.

© Kalasalingam academy of research and education 108


Steps to connect a Java Application to Database

The following 5 steps are the basic steps involve in connecting a Java
application with Database using JDBC.
Register the Driver
Create a Connection
Create SQL Statement
Execute SQL Statement
Closing the connection
Register the Driver
Class.forName() is used to load the driver class explicitly.
Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

© Kalasalingam academy of research and education 109


Steps to connect a Java Application to Database(Cond..)
Create a Connection
getConnection() method of DriverManager class is used to create a connection.

© Kalasalingam academy of research and education 110


Steps to connect a Java Application to Database(Cond..)

Create SQL Statement


createStatement() method is invoked on current Connection object to create a SQL Statement.

© Kalasalingam academy of research and education 111


Steps to connect a Java Application to Database
Example to create a SQL statement
Statement s=con.createStatement();
Execute SQL Statement
executeQuery() method of Statement interface is used to execute
SQL statements.
Syntax
public ResultSet executeQuery(String query) throws SQLException
Example to execute a SQL statement
Listing 30:execute.java
ResultSet rs=s. executeQuery (" select * from user ");
while (rs. next ()) {
System . out. println (rs. getString (1)+ " “+rs. getString1 (2)); }

© Kalasalingam academy of research and education 112


Steps to connect a Java Application to Database(Cond..)

Closing the connection


After executing SQL statement you need to close the connection and release the session. The
close() method of Connection interface is used to close the connection.

Example of closing a connection


con.close();

© Kalasalingam academy of research and education 113


JDBC Example.java

© Kalasalingam academy of research and education 114


Output

© Kalasalingam academy of research and education 115


Topic 1
JDBC

Topic 2
JDBC Structure

Topic 3
Drivers

Topic 4
JDBC 4.0 API

Topic 5

JDBC Connection
Fourth Lesson Summary
Understand about Java Database connectivity, its structure, JDBC
& ODBC Drivers, Steps to connect to a Database, JDBC Application
Programming Interface, Example Program for JDBC Connection

© Kalasalingam academy of research and education 116


Course Progress (use before starting new lesson)
Lesson 1. Networking Basics

Lesson 2. Client-Server Programming

Lesson 3. Relational Database

Lesson 4. JDBC

Lesson 5. Case Studies

© Kalasalingam academy of research and education 117


Case Study

In the realm of Teradata, every nation has one national bank and its own installment door related with it. They all are
associated with one another using tree geography. On the off chance that a client is attempting to move assets from
country to then the assets need to move through all transitional banks connecting and .

Tree geography is organized like a tree, where it's anything but a root hub, middle hubs and leaves. Root hub is the head
hub of the construction, and the leaves are the last hubs, which has no further youngster hubs. This construction is
organized in a various leveled structure, every hub can have quite a few the kid nodes.

Let's say there are central banks in the Teradata world and every one of them are exceptionally numbered between .
Root bank will be addressed by . All edges are bidirectional in nature, i.e., an assets can stream toward any path. It is
ensured that there will be by and large one way between each pair of banks. There will be connections which will be
utilized to interface the banks.

© Kalasalingam academy of research and education 118


Topic 1
Case Study 1:TCP Server

Topic 2
Case Study 2:UDP Server

Topic 3
Case Study 3:JDBC Connection

Fifth Lesson Summary


Learned about TCP Server, UDP Server and JDBC
Connection and worked on it.

© Kalasalingam academy of research and education 119


Thank You!

© Kalasalingam academy of research and education 120

You might also like