0% found this document useful (0 votes)
4 views27 pages

Java Chapter 5

The document discusses Java's I/O operations, detailing byte and character streams, their classes, and methods for reading and writing console input and files. It also covers applets, their architecture, and how to embed them in HTML, along with networking basics in Java, emphasizing the role of sockets and protocols in network communication. Overall, it serves as a comprehensive guide to I/O operations, applet fundamentals, and networking in Java.

Uploaded by

echovaultedits
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)
4 views27 pages

Java Chapter 5

The document discusses Java's I/O operations, detailing byte and character streams, their classes, and methods for reading and writing console input and files. It also covers applets, their architecture, and how to embed them in HTML, along with networking basics in Java, emphasizing the role of sockets and protocols in network communication. Overall, it serves as a comprehensive guide to I/O operations, applet fundamentals, and networking in Java.

Uploaded by

echovaultedits
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

UNIT-5 (I/O Operations)

LECTURE - 1
I/O Basics, Reading Console Input, Writing Console Output, Reading
and Writing Files

Java’s I/O system is quite large, containing many classes, interfaces, and methods. Java
programs perform I/O through streams. An I/O stream is an abstraction that either produces
or consumes information. A stream is linked to a physical device by the Java I/O system. All
streams behave in the same manner, even if the actual physical devices they are linked to
differ.

Byte Streams and Character Streams


Byte streams provide a convenient means for handling input and output of bytes. They are
used when reading or writing binary data. They are especially helpful when working with files.
Character streams are designed for handling the input and output of characters. They use
Unicode and, therefore, can be internationalized. Also, in some cases, character streams are
more efficient than byte streams.

The Byte Stream Classes


Byte streams are defined by using two class hierarchies. At the top of these are two abstract
classes: InputStream and OutputStream. InputStream defines the characteristics common
to byte input streams and OutputStream describes the behavior of byte output streams.

Byte Stream Classes in [Link].


Unit-5 [Link]. – AI&DS-IV I/O Operations

The Character Stream Classes


Character streams are defined by using two class hierarchies topped by these two abstract
classes: Reader and Writer. Reader is used for input, and Writer is used for output. Concrete
classes derived from Reader and Writer operate on Unicode character streams.

The Character Stream I/O Classes in [Link].

The Predefined Streams


All Java programs automatically import the [Link] package. This package defines a class
called System, which encapsulates several aspects of the runtime environment. It also
contains three predefined stream variables called in, out, and err. [Link] refers to the
standard output stream. [Link] refers to standard input, which is by default the keyboard.
[Link] refers to the standard error stream. [Link] is an object of type InputStream,
[Link] and [Link] are objects of type PrintStream.

1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

Using the Byte Stream


At the top of the byte stream hierarchy are the InputStream and OutputStream classes. In
general, the methods in InputStream and OutputStream can throw an IOException on error.

List of a few Methods defined by InputStream class.

2
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

List of a few Methods defined by outputStream class.

Reading Console Input


Originally, the only way to perform console input was to use a byte stream, and most of Java
code still uses the byte streams exclusively. Now, we can use byte or character streams. It
makes our program easier to internationalize and easier to maintain.

As [Link] is an instance of InputStream, we automatically have access to the methods


defined by InputStream. It means we can use the read( ) method to read bytes from
[Link].

There are three versions of read( ):

int read( ) throws IOException


→This reads a single character.

int read(byte data[ ]) throws IOException


→This reads bytes from the input stream and puts them into data until either the array is
full, the end of stream is reached, or an error occurs.

int read(byte data[ ], int start, int max) throws IOException


→This reads input into data beginning at the location specified by start. Up to max bytes are
stored. It returns the number of bytes read, or when an attempt is made to read at the end
of the stream.

Example-
import [Link].*;
public class ReadBytesDemo {
public static void main(String args[]) throws IOException

3
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

{
byte data[] = new byte[100];
[Link]("Enter Some Charaters : ");
[Link](data);
[Link]("You Entered : ");
for(int i=0;i<[Link];i++)
{
[Link]((char) data[i]);
}
}
}

Output-
Enter Some Charaters :
The quick brown fox jumps over the lazy dog.
You Entered : The quick brown fox jumps over the lazy dog.

Writing Console Output


Java originally provided only byte streams for console output. As [Link] is a byte stream,
however, byte-based console output is still widely used. Console output is most easily
accomplished with print( ) and println( ), with which we are already using in our programs.
These methods are defined by the class.

Since PrintStream is an output stream derived from OutputStream, it also implements the
low-level method write( ) and it is possible to write to the console by using write( ).
PrintStream supplies two additional output methods: printf( ) and format( ). Both give us
detailed control over the precise format of data that we output.

The simplest form of write( ) defined by PrintStream is:

void write(int byteval)


→It writes the byte specified by byteval to the file.

Example-
public class WriteDemo {
public static void main(String args[])
{
int a;
a='A';
[Link](a);
[Link]('\n');
}
}

4
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

Output-
A

We will not often use write( ) to perform console output (although it might be useful in some
situations), that’s why print( ) and println( ) are substantially easier to use.

Reading and Writing Files


Java provides a number of classes and methods that allows us to read and write files. To do
this, reading and writing files using byte streams is very common.

To create a byte stream linked to a file, we use FileInputStream or FileOutputStream.

Reading a File
A file is opened for input by creating a FileInputStream object.

FileInputStream(String fileName) throws FileNotFoundException

Here, fileName specifies the name of the file we want to open. If the file does not exist, then
FileNotFoundException is thrown. FileNotFoundException is a subclass of IOException.

To read from a file, we can use read( ) as:

int read( ) throws IOException

After reading from a file, we must close it by calling close( ) as:

void close( ) throws IOException


→ Closing a file releases the system resources allocated to the file, allowing them to be used
by another file.

Example-
Java File - [Link]
import [Link];
import [Link];
import [Link];

public class ReadFileDemo {


public static void main(String args[])
{
int i;
FileInputStream fin;
if([Link] != 1)

5
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

{
[Link]("Usage: ReadFileDemo File");
return;
}

try
{
fin = new FileInputStream(args[0]);
//fin = new FileInputStream("[Link]");
}
catch(FileNotFoundException exc)
{
[Link]("File not found");
return;
}

try
{
//read bytes until EOF is encountered
do
{
i = [Link](); //read from the file.
if(i != -1)
{
[Link]((char) i);
}
}while(i != -1);
}
catch(IOException exc)
{
[Link]("Error reading file.");
}

try
{
[Link](); //closing the file.
}
catch(IOException exc)
{
[Link]("Error closing file.");
}
}
}

Text File- [Link] (The file which we are reading with the java program)
The quick brown fox jumps over the lazy dog.

Output-

6
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

The quick brown fox jumps over the lazy dog.

Writing to a File
To open a file for output we need to create a FileOutputStream object as:

FileOutputStream(String fileName) throws FileNotFoundException


→With this form of FileOutputStream, when an output file is opened, any preexisting file by
the same name is destroyed.

FileOutputStream(String fileName, boolean append) throws FileNotFoundException


→With this form of FileOutputStream, if append is true, then output is appended to the end
of the file. Otherwise, the file is overwritten.

If the file cannot be created, then FileNotFoundException is thrown.

To write to a file, we will use the write( ) method as:

void write(int byteval) throws IOException


→ This method writes the byte specified by byteval to the file. Although byteval is declared
as an integer, only the loworder 8 bits are written to the file. If an error occurs during writing,
an IOException is thrown.

Once we are done with an output file, we must close it using close( ) as:

void close( ) throws IOException

Example-
Java [Link]
import [Link];
import [Link];
import [Link];

public class WritetoFileDemo {


public static void main(String args[])
{
int i;
FileInputStream fin = null;
FileOutputStream fout = null;

if([Link] != 2)
{
[Link]("Usage: WritetoFileDemo from to");
return;
}

7
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

//Copy a file
try
{
//Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);

do
{
i = [Link](); //Read from a file
if(i != -1 )
{
[Link](i); //Write to Other File.
}
}while(i != -1);
}
catch(IOException exc)
{
[Link]("I/O Error: " + [Link]());
}
finally
{
try
{
if(fin != null)
{
[Link]();
}
}
catch(IOException exc)
{
[Link]("Error Closing Output File");
}
}
}
}

Input [Link] (which is already exists and having some data).


Output [Link] (Which would be created by executing the java program).

8
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 2
Applets: Applet Fundamentals, Applet Architecture

At the time of Java’s creation, one of its most exciting features was the applet. An applet is a
special kind of Java program that is designed to be transmitted over the Internet and
automatically executed inside a Java-compatible web browser. These are the programs that
you can embed in web pages to provide some intelligence like play sounds, play animations.

Important points about Applets


➢ Java enables us to write small programs called applets.
➢ An applet is a window based programming environment.
➢ Applete programs are java classes that extend that [Link] class and are
enabaled by reference with HTML page.
➢ Applets are not stand-alone programs.
➢ Applets can’t read or write local files, check for the existence of files, execute
programs on the local machine, etc. These restrictions are for security reasons.

Applet Architecture
The database server is connected to the JDBC driver, which is connected to the applet. The
applet is also connected to a browser, which is connected to a web server that communicates
with the database.

Courtesy - [Link]

→Because of waning browser support for applets (and other factors), JDK 9 deprecated the
entire applet API and With the release of JDK 11, applet support has been removed.
LECTURE - 3
The HTML Applet Tag, Passing Parameters to Applets

Applets are embedded in HTML documents with the <APPLET> tag. It contains attributes that
identify the applet to be displayed and, optionally, give the web browser hints about how it
should be displayed. Attributes are name/value pairs that are interpreted by a web browser
or appletviewer. Applets have both an opening <APPLET> and a closing </APPLET> tag.
Sandwiched between these can be any number of <PARAM> tags that contain data to be
passed to the applet:

<APPLET attribute
attribute ... >
<PARAM parameter >
<PARAM parameter >
...
</APPLET>

The definition of the <APPLET> tag lists a fixed set of recognized attributes; specifying an
incorrect or nonexistent attribute should be considered an HTML error. Three attributes are
required in the <APPLET> tag. These are width, height and code or object.

Parameters
Parameters are analogous to command-line arguments; they provide a way to pass
information to an applet. Each <PARAM> tag contains a name and a value that are passed as
strings to the applet:

<PARAM name = parameter_name value = parameter_value>

There is no fixed set of parameter names or values. it’s up to the applet to interpret the
parameter name/value pairs that are passed to it. Any number of parameters can be
specified, and the applet may choose to use or ignore them as it sees fit. The applet might
also consider parameters to be either optional or required, and act accordingly.

How to Run Applet


There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
2. Use an applet viewer to test your applet -> type at command line-
appletviewer [Link]
Unit-5 [Link]. – AI&DS-IV I/O Operations

Example-
[Link]

import [Link].*;
import [Link].*;
/*
<applet code="apletdemo2" width=300 height=50>
</applet>
*/
public class apletdemo2 extends Applet
{
String msg;
// set the foreground and background colors.
public void init()
{
setBackground([Link]);
setForeground([Link]);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg += " Inside paint( ).";
[Link](msg, 10, 30);
}
}

[Link]
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "[Link]" width = "320" height = "120">
If your browser was Java-enabled, a "Applet Demo"
message would appear here.
</applet>
<hr>
</html>

1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

Output-

2
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 4
Networking Basics, Java and the Net

One of the most important reasons that Java became the premier language for network
programming are the classes defined in the [Link] package.

Networking Basics
➢ At the core of Java’s networking support is the concept of a socket. A socket identifies
an endpoint in a network. Sockets are at the foundation of modern networking
because a socket allows a single computer to serve many different clients at once, as
well as to serve many different types of information. This is accomplished through the
use of a port, which is a numbered socket on a particular machine.
➢ A server process is said to "listen" to a port until a client connects to it. A server is
allowed to accept multiple clients connected to the same port number, although each
session is unique. To manage multiple client connections, a server process must be
multithreaded or have some other means of multiplexing the simultaneous I/O.
➢ Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level
routing protocol that breaks data into small packets and sends them to an address
across a network, which does not guarantee to deliver said packets to the destination.
➢ Transmission Control Protocol (TCP) is a higher-level protocol that manages to
robustly string together these packets, sorting and retransmitting them as necessary
to reliably transmit data. A third protocol, User Datagram Protocol (UDP), sits next to
TCP and can be used directly to support fast, connectionless, unreliable transport of
packets.
➢ Hypertext Transfer Protocol (HTTP) is the protocol that web browsers and servers use
to transfer hypertext pages and images. It is a quite simple protocol for a basic page-
browsing web server. When a client requests a file from an HTTP server, an action
known as a hit, it simply sends the name of the file in a special format to a predefined
port and reads back the contents of the file.
➢ A key component of the Internet is the address (IP Address). Every computer on the
Internet has one address. An Internet address is a number that uniquely identifies
each computer on the Net. Originally, all Internet addresses consisted of 32-bit values,
organized as four 8-bit values which was specified by IPv4. IPv6 uses a 128-bit value
to represent an address.
➢ As the numbers of an IP address describe a network hierarchy, the name of an Internet
address, called its domain name, describes a machine’s location in a name space.
➢ An Internet domain name is mapped to an IP address by the Domain Naming Service
(DNS).
Unit-5 [Link]. – AI&DS-IV I/O Operations

Java and the Net


The [Link] package contains Java’s original networking features. It supports TCP/IP both by
extending the already established stream I/O interface and by adding the features required
to build I/O objects across the network. The classes contained in the [Link] package are:

The [Link] package’s interfaces are:

InetAddress
The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address. We interact with this class by using the name of an IP host, which is
more convenient and understandable than its IP address.

Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress object, we 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.

1
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 5
TCP/IP Client Sockets URL, URL Connection, TCP/IP Server Sockets

TCP/IP Client Sockets


TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point,
stream-based connections between hosts on the Internet. A socket can be used to connect
Java’s I/O system to other programs that may reside either on the local machine or on any
other machine on the Internet, subject to security constraints.

TCP/IP Server Sockets


The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports. ServerSockets are quite different from
normal Sockets. When we create a ServerSocket, it will register itself with the system as
having an interest in client connections. The constructors might throw an IOException under
adverse conditions.

Types of TCP Sockets


There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The
ServerSocket class is designed to be a "listener", which waits for clients to connect before
doing anything. The Socket class is for clients. It is designed to connect to server sockets and
initiate protocol exchanges. The creation of a Socket object implicitly establishes a
connection between the client and server. We can gain access to the input and output
streams associated with a Socket by use of the getInputStream( ) and getOuptutStream( ).
Each can throw an IOException if the socket has been invalidated by a loss of connection.

Several other methods are available including –


▪ connect( )-allows us to specify a new connection .
▪ isConnected( )-returns true if the socket is connected to a server.
▪ isBound( )-returns true if the socket is bound to an address.
▪ isClosed( )-returns true if the socket is closed.
▪ close( )-to close a socket.

Example –
The following example showing how to use Socket and ServerSocket Class to make
connection between client and server.

[Link](Using ServerSocket)
import [Link].*;
import [Link].*;

public class ServerExp


{
Unit-5 [Link]. – AI&DS-IV I/O Operations

public static void main(String[] args)


{
try
{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();//establishes connection

DataInputStream dis=new DataInputStream([Link]());

String str=(String)[Link]();
[Link]("message= "+str);

[Link]();

}
catch(Exception e)
{
[Link](e);
}
}
}

ClientExp(Using Socket)
import [Link].*;
import [Link].*;

public class ClientExp


{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",3333);

DataOutputStream dout=new DataOutputStream([Link]());

[Link]("Hello Server");
[Link]();

[Link]();
[Link]();

}catch(Exception e)
{
[Link](e);
}
}
}

1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

Output(On Server Machine)


message= Hello Server

URL
The URL provides a reasonably intelligible form to uniquely identify or address information
on the Internet. URLs are ubiquitous. Every browser uses them to identify information on the
Web. Within Java’s network class library, the URL class provides a simple, concise API to
access information across the Internet using URLs. All URLs share the same basic format,
although some variation is allowed.

A URL specification is based on four components-


➢ The first is the protocol to use, separated from the rest of the locator by a colon (:).
Common protocols are HTTP, FTP, gopher, and file, although these days almost
everything is being done via HTTP(Hypertext Transfer Protocol) (in fact, most
browsers will proceed correctly if you leave off the "[Link] from our URL
specification) or HTTPS(Hypertext Transfer Protocol Secure).
➢ The second component is the host name or IP address of the host to use. This is
delimited on the left by double slashes (//) and on the right by a slash (/) or optionally
a colon (:).
➢ The third component, the port number, is an optional parameter, delimited on the
left from the host name by a colon (:) and on the right by a slash (/). (It defaults to
port 80, the predefined HTTP port; thus, ":80" is redundant.)
➢ The fourth part is the actual file path. Most HTTP servers will append a file named
[Link] or [Link] to URLs that refer directly to a directory resource.

Example-
import [Link];
import [Link];

public class URLDemo {


public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("[Link]
[Link]("Protocol: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
//[Link]("Ext: " + [Link]());
}
}

2
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

Output-
Protocol: https
Port: -1 → port is –1. This means that a port was not explicitly set.
Host: [Link]
File: /WhatsNew

URLConnection
URLConnection is a general-purpose class for accessing the attributes of a remote resource.
Once we make a connection to a remote server, we can use URLConnection to inspect the
properties of the remote object before actually transporting it locally. These attributes are
exposed by the HTTP protocol specification and, as such, only make sense for URL objects
that are using the HTTP protocol. URLConnection defines several methods.

Example-
import [Link];
import [Link];
import [Link];
import [Link];

public class UrlConnectionDemo {


public static void main(String args[]) throws Exception
{
int c;
URL hp = new URL("[Link]
URLConnection hpCon = [Link]();

long d = [Link]();
if(d==0)
{
[Link]("No date information.");
}
else
{
[Link]("Date: " + new Date(d));
}

[Link]("Content-Type: " + [Link]());

d = [Link]();

if(d==0)
{
[Link]("No expiration information.");
}

3
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

else
{
[Link]("Expires: " + new Date(d));
}

d = [Link]();
if(d==0)
{
[Link]("No last-modified information.");
}
else
{
[Link]("Last-Modified: " + new Date(d));
}

long len = [Link]();

if(len == -1)
{
[Link]("Content length unavailable.");
}
else
{
[Link]("Content-Length: " + len);
}

if(len != 0)
{
[Link]("=== Content ===");
InputStream input = [Link]();
while(((c = [Link]()) != -1))
{
[Link]((char) c);
}
[Link]();
}
else
{
[Link]("No content available.");
}
}
}

This program establishes an HTTP connection to [Link] over port 80. It then
displays several header values and retrieves the content.

4
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

HttpURLConnection
Java provides a subclass of URLConnection that provides support for HTTP connections. This
class is called HttpURLConnection. We obtain an HttpURLConnection in the same way just
shown, by calling openConnection() on a URL object, but we must cast the result to
HttpURLConnection. Once we have obtained a reference to an HttpURLConnection object,
we can use any of the methods inherited from URLConnection. We can also use any of the
several methods defined by HttpURLConnection.

The URI Class


The URI class encapsulates a Uniform Resource Identifier (URI). URIs are similar to URLs. In
fact, URLs constitute a subset of URIs. A URI represents a standard way to identify a resource.
A URL also describes how to access the resource.

Cookies
The [Link] package includes classes and interfaces that help manage cookies and can be
used to create a stateful (as opposed to stateless) HTTP session. The classes are
CookieHandler, CookieManager, and HttpCookie. The interfaces are CookiePolicy and
CookieStore.

5
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 6
Database Connectivity

A database is an organized collection of data. There are many different strategies for
organizing data to facilitate easy access and manipulation. A database management system
(DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many
users. Database Management Systems allow for the access and storage of data without
concern for the internal representation of data. Java programs communicate with databases
and manipulate their data using the Java Database Connectivity (JDBC) API.

Java Database Connectivity (JDBC)


Java Database Connectivity (JDBC) is an application programming interface for the Java
programming language, which defines how a client may access a database. It is a Java-based
data access technology used for Java database connectivity.

JDBC is a standard Java API for database-independent connectivity between the Java
programming language and a wide range of databases. The JDBC library includes APIs for
each of the tasks commonly associated with database usage:
❖ Making a connection to a database
❖ Creating SQL or MySQL statements
❖ Executing SQL or MySQL queries in the database
❖ Viewing & Modifying the resulting records

JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables,
like - Java Applications, Java Applets, Java Servlets, Java ServerPages (JSPs), Enterprise
JavaBeans (EJBs). JDBC provides the same capabilities as ODBC, allowing Java programs to
contain database-independent code.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general JDBC Architecture consists of two layers:
❖ JDBC API: This provides the application-to-JDBC Manager connection.
❖ JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Unit-5 [Link]. – AI&DS-IV I/O Operations

JDBC Architectural Diagram

Common JDBC Components


The JDBC API provides the following interfaces and classes:

DriverManager : This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver by using communication
subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to
establish a database Connection.

Driver : This interface handles the communications with the database server. We will interact
directly with Driver objects very rarely. Instead, we use DriverManager objects, which
manages objects of this type. It also abstracts the details associated with working with Driver
objects.

Connection : The connection object represents communication context, i.e., all


communication with database is through connection object only.

Statement : We use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.

ResultSet : These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.

SQLException : This class handles any errors that occur in a database application.

1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

Relational Databases
Most popular database systems are relational databases. A relational database is a logical
representation of data that allows the data to be accessed without consideration of its
physical structure. A relational database stores data in tables. Tables are composed of rows,
and rows are composed of columns in which values are stored. One column of each row can
be the table’s primary key – a column (or group of columns) with a unique value that cannot
be duplicated in other rows. This guarantees that each row can be identified by its primary
key.

Structured Query Language (SQL)


A language called Structured Query Language (SQL) - pronounced “sequel,” or as its
individual letters - is the international standard language used almost universally with
relational databases to perform queries (i.e., to request information that satisfies given
criteria) and to manipulate data.
SQL Keywords Description
SELECT Retrieves data from one or more tables.
FROM Tables involved in the query. Required in
every SELECT.
WHERE Criteria for selection that determine the
rows to be retrieved, deleted or updated.
Optional in a SQL query or a SQL statement.
GROUP BY Criteria for grouping rows. Optional in a
SELECT query.
ORDER BY Criteria for ordering rows. Optional in a
SELECT query.
INNER JOIN Merge rows from multiple tables.
INSERT Insert rows into a specified table.
UPDATE Update rows in a specified table.
DELETE Delete rows from a specified table.

Basic SELECT Query - A SQL query “selects” rows and columns from one or more tables in a
database. The basic form of a SELECT query is-

SELECT * FROM tableName

WHERE Clause - It’s necessary to locate rows in a database that satisfy certain selection
criteria. Only rows that satisfy the selection criteria (formally called predicates) are selected.
SQL uses the optional WHERE clause in a query to specify the selection criteria for the query.
The basic form of a query with selection criteria is-

SELECT columnName1, columnName2, … FROM tableName WHERE criteria

2
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

ORDER BY Clause - The rows in the result of a query can be sorted into ascending or
descending order by using the optional ORDER BY clause. The basic formof a query with an
ORDER BY clause is-

SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC


SELECT columnName1, columnName2,…FROM tableName ORDER BY column DESC

Merging Data from Multiple Tables: INNER JOIN - It’s necessary to merge data from multiple
tables into a single result. Referred to as joining the tables, this is specified by an INNER JOIN
operator, which merges rows from two tables by matching values in columns that are
common to the tables. The basic form of an INNER JOIN is-

SELECT columnName1, columnName2, …


FROM table1
INNER JOIN table2
ON [Link] = [Link]

INSERT Statement - The INSERT statement inserts a row into a table. The basic form of this
statement is-

INSERT INTO tableName ( columnName1, columnName2, …, columnNameN )


VALUES ( value1, value2, …, valueN )

UPDATE Statement - An UPDATE statement modifies data in a table. Its basic form is-
UPDATE tableName
SET columnName1 = value1, columnName2 = value2, …, columnNameN = valueN
WHERE criteria

Creating JDBC Application


There are following seven steps involved in building a JDBC application:
➢ Import the packages - Requires that we include the packages containing the JDBC
classes needed for database programming. Most often, using import [Link].* will
suffice.

➢ Register the JDBC driver . Requires that we initialize a driver so we can open a
communications channel with the database.

➢ Open a connection . Requires using the [Link]() method to


create a Connection object, which represents a physical connection with the
database.

3
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

➢ Preparing a query . Create an object of prepareStatement to assign a SQL statement


to execute a query.

➢ Execute a query . Requires using an object of type Statement for building and
submitting an SQL statement to the database.

➢ Extract data from result set . Requires that we use the appropriate [Link]()
method to retrieve the data from the result set.

➢ Clean up the environment . Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.

Example-
//Setp 1 - Import required packages
import [Link].*;

class mysqlcon
{
public static void main(String args[])
{
try
{
//Step 2 - Register JDBC driver
[Link]("[Link]");

//Step 3 - Open a connection


Connection con =
[Link]("jdbc:mysql://localhost:3306/stdmarks", "root",
"root");

//Step 4 - Preparing Query


PreparedStatement ps = [Link]("select * from stddata
where perc > 60");

//Step 5 - Execute a Query


ResultSet rs = [Link](); //execute

[Link]("Students having marks > 60 are:");

//Step 6 - Extracting Data


while([Link]())
[Link]([Link](2));

//Step 7 - Clean-up environment


[Link]();
}

4
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations

catch(Exception e)
{
//Exception Handling
[Link]("Error" + [Link]());
}
}
}

The above example extracting data from a mysql database stdmarks and executing a query
which retrive data of those students having marks greater than 60.

Example(Inserting Data in Database using JDBC)-


import [Link].*;
class mysqlinsdata
{
public static void main(String args[])
{
try
{

[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/stdmarks", "root",
"root");
//Statement stat = [Link]();
String sql = "insert into stddata (stdname, stdage, stdm1, stdm2,
stdm3, totmarks, perc, results) values('bcd',18,74,66,80,216,73.33,'First')";
PreparedStatement pst = [Link](sql);
int numRowsChanged = [Link](sql);
[Link](numRowsChanged);
//ResultSet rs = [Link]("insert into stdmarks (stdname,
stdage, stdm1, stdm2, stdm3, totmarks, perc, results)
values(‘abc’,18,70,66,80,216,72.0,’First’)");
[Link]();
}
catch(Exception e)
{
[Link]("Error" + [Link]());
}
}
}

In this example we are inserting data in an existing database.

5
Notes By: - Sanjeev Khatri (Assoc. Professor)

You might also like