0% found this document useful (0 votes)
9 views31 pages

Oopj Unit-5

Another oops ?

Uploaded by

ramgandham973
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)
9 views31 pages

Oopj Unit-5

Another oops ?

Uploaded by

ramgandham973
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/ 31

Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.

Neelima

Object Oriented Programming Through JAVA


[B23CS2103]
Unit-V
_______________________________________________________________________________________________________
SYLLABUS:
File IO: Introduction, Hierarchy of Stream classes, Byte Streams, Character streams.
_______________________________________________________________________________________________________

File
A file is a named location that can be used to store related information. For example,
main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories. A directory inside a directory is known
as subdirectory.

In Java, a File is an abstract data type. There are several File Operations like creating a
new File, getting information about File, writing into a File, reading from a
File and deleting a File.

Types of Files in java

A file can be classified into two types based on the way the file stores the data. They are as
follows:
• Text Files
• Binary Files

1. Text Files
A text file contains data in the form of Unicode characters and is generally used to store a
stream of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.

2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of Unicode characters.
They contain data that is stored in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can
only be read by a program.
• More secure as they are not easily readable.

CIC Sagi Rama Krishnam Raju Engineering College(A) 1


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

• They are generally stored with .bin file extension.

Java File Handling

File handling is an important part of any application. Java has several methods for creating,
reading, updating, and deleting files.

The File class from the java.io package, allows us to work with files. To use the File class,
create an object of the class, and specify the filename or directory name:

Example:
import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files.

Method Type Description


canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

Stream

In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows
us to read from and write to it. A stream can be linked to a data source, or data destination,
like a console, file or network connection by java IO system. The stream-based IO
operations are faster than normal IO operations.

The Stream is defined in the java.io package.

CIC Sagi Rama Krishnam Raju Engineering College(A) 2


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

In java, the stream-based IO operations are performed using two separate streams input
stream and output stream. The input stream is used for input operations, and the output
stream is used for output operations. The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to
the console.

• System.out: standard output stream for console output operations.


• System.in: standard input stream for console input operations.
• System.err: standard error stream for console error output operations.

The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.
Java provides two types of streams, and they are as follows.

• Byte Stream
• Character Stream

Hierarchy of Stream classes

The following picture shows how streams are categorized, and various built-in classes used
by the java IO system.

CIC Sagi Rama Krishnam Raju Engineering College(A) 3


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Character Streams in Java:

Character streams in Java are designed for handling the input and output of characters.
They use 16-bit Unicode characters.

Character streams are more efficient than byte streams. They are mainly used for reading
or writing to character or text-based I/O such as text files, text documents, XML, and HTML
files.

Text files are those files that are human readable. For example, a .txt file that contains
human-readable text. This file is created with a text editor such as Notepad in Windows.

Character streams that are used for reading are called readers and for writing are called
writers. They are represented by the abstract classes of Reader and Writer in Java.

Writer class

The writer class is designed to write 16-bit Unicode characters to the output stream. Since
the Writer class is an abstract class, it cannot be instantiated.
Therefore, the subclasses of the Writer class are used to write the characters onto the
output stream. The hierarchy diagram of subclasses of the Writer class is shown in the
below figure.

Writer Subclasses:

1. BufferedWriter: This class is used to write characters to the buffered output character
stream.
2. FileWriter: This output stream class writes characters to the file.
3. CharArrayWriter: This output stream class writes the characters to the character
array.

CIC Sagi Rama Krishnam Raju Engineering College(A) 4


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

4. OutpuStreamWriter: This output stream class translates or converts from bytes to


characters.
5. PipedWriter: This class writes the characters to the piped output stream.
6. StringWriter: This output stream class writes the characters to the string.
7. PrintWriter: This output stream class contains print() and println().
8. FilterReader: This class is used to write characters on the underlying character output
stream.

Writer Class Methods in Java

The Writer class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description


void flush()
1
It flushes the output steam by forcing out buffered bytes to be written out.
void write(char[] cbuf)
2
It writes a whole array(cbuf) to the output stream.
void write(char[] cbuf, int off, int len)
3
It writes a portion of an array of characters.
void write(int c)
4
It writes single character.
void write(String str)
5
It writes a string.
void write(String str, int off, int len)
6
It writes a portion of a string.
Writer append(char c)
7
It appends the specified character to the writer.
Writer append(CharSequence csq)
8
It appends the specified character sequence to the writer
Writer append(CharSequence csq, int start, int end)
9 It appends a subsequence of the specified character sequence to the
writer.
void close()
10 It closes the output stream and also frees any resources connected with
this output stream.

Reader class

The hierarchy of Reader Stream Classes is shown in the figure.

CIC Sagi Rama Krishnam Raju Engineering College(A) 5


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Reader Subclasses:

1. BufferedReader: This class is used to read characters from the buffered input
character stream.
2. CharArrayReader: This class is used to read characters from the char array or
character array.
3. FileReader: This class is used to read characters (or contents) from a file.
4. FilterReader: This class is used to read characters from the underlying character input
stream.
5. InputStreamReader: This class is used to translate (or convert) bytes to characters.
6. PipeReader: This class is used to read characters from the connected piped output
stream.
7. StringReader: This class is used to read characters from a string.
8. PushBackReader: This class allows one or more characters to be returned to the input
stream.

Reader Class Methods in Java:

The Reader class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description


1 int read()
It reads the next character from the input stream.
2 int read(char[] cbuffer)
It reads a chunk of characters from the input stream and store them in its
byte array, cbuffer.
3 int read(char[] cbuf, int off, int len)
It reads charaters into a portion of an array.
4 int read(CharBuffer target)

CIC Sagi Rama Krishnam Raju Engineering College(A) 6


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

It reads characters into the specified character buffer.


5 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a
line feed ('\n'), a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.
6 boolean ready()
It tells whether the stream is ready to be read.
7 void close()
It closes the input stream and also frees any resources connected with this
input stream.

Writing:
Using FileWriter:
import java.io.*;
class File1
{
public static void main(String args[])throws Exception
{
File f1=new File("abcd.txt");
f1.createNewFile();
FileWriter fw=new FileWriter(f1);
fw.write(78);
fw.write('\n');
fw.write('n');
fw.write('\n');
fw.write("neelima");
fw.write('\n');
char ch[]={'n','e','e','l','u'};
fw.write(ch);
System.out.println(f1.exists());
fw.close();
}
}

Using BufferedWriter:
import java.io.*;
class File2
{
public static void main(String args[])throws Exception
{
FileWriter fw=new FileWriter("abcd.txt",true);
BufferedWriter br=new BufferedWriter(fw);
br.newLine();
br.write(82);
br.newLine();
br.write('r');
br.newLine();
br.write("raghuram");
br.newLine();

CIC Sagi Rama Krishnam Raju Engineering College(A) 7


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

char ch[]={'r','a','g','h','u'};
br.write(ch);
br.close();
}
}

Using PrintWriter:

import java.io.*;
class File3
{
public static void main(String args[])throws Exception
{
FileWriter fw=new FileWriter("abcd.txt",true);
PrintWriter pr=new PrintWriter(fw);
pr.println(82);
char ch[]={'g','a','g','a','n'};
pr.println(ch);
String str="hello";
pr.println(str);
pr.println(12.5);
pr.println(true);
pr.close();
}
}

Reading:
Using FileReader:
import java.io.*;
class FileReader1
{
public static void main(String args[]) throws Exception
{
FileReader fr=new FileReader("abcd.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close();
}
}

Using BufferedReader:
import java.io.*;
class BufferedReader1
{
public static void main(String args[]) throws Exception
{

CIC Sagi Rama Krishnam Raju Engineering College(A) 8


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

FileReader fr=new FileReader("abcd.txt");


BufferedReader br=new BufferedReader(fr);
String s;
while((s=br.readLine())!=null)
{
System.out.println(s);
}
br.close();
}
}

Coping:

import java.io.*;
public class FileCopy
{
public static void main(String[] args) throws Exception
{
String sf = "abcd.txt";
String df = "12345.txt";

// Initialize FileReader and FileWriter objects


FileReader r = null;
FileWriter w = null;

try
{
// Create a FileReader to read the content of the source file
r = new FileReader(sf);
// Create a FileWriter to write the content to the destination file
w = new FileWriter(df);

int c;
// Read each character from the source file and write it to the destination file
while ((c = r.read()) != -1)
{
w.write(c);
}
System.out.println("File copied successfully!");
}
catch (IOException e)
{
// Handle exceptions (file not found, read/write errors, etc.)
System.err.println("Error occurred: " + e.getMessage());
}
finally
{
try
{

CIC Sagi Rama Krishnam Raju Engineering College(A) 9


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

// Close the FileReader and FileWriter to release resources


if (r!= null)
{
r.close();
}
if (w != null)
{
w.close();
}
}
catch (IOException e)
{
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}

Byte Streams in Java:

Byte streams in Java are designed to provide a convenient way for handling the input and
output of bytes (i.e., units of 8-bits data). We use them for reading or writing to binary data
I/O.

Byte streams are especially used when we are working with binary files such as executable
files, image files, and files in low-level file formats such as .zip, .class, .obj, and .exe.

Binary files are those files that are machine readable. For example, a Java class file is an
extension of “.class” and humans cannot read it.

It can be processed by low-level tools such as a JVM (executable java.exe in Windows) and
java disassembler (executable javap.exe in Windows).

Another real-time example is storing a photo in a .bmp or .jpeg file. These files are certainly
not human readable. Photo editing or image manipulation software can only process them.

Byte streams that are used for reading are called input streams and for writing are
called output streams. They are represented by the abstract classes of InputStream and
OutputStream in Java.

Input Stream Classes:


Input stream classes that are used to read bytes include a super class known as
Inputstream. The input stream class defines methods for performing input functions.

CIC Sagi Rama Krishnam Raju Engineering College(A) 10


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Important Methods in the InputStream Class:

Output Stream Classes:


Output stream classes are derived from the base class Outputstream like InputStream, the
OutputStream is an abstract class and therefore we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.

Important Methods in the OutputStream Class:

CIC Sagi Rama Krishnam Raju Engineering College(A) 11


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Writing:
import java.io.FileOutputStream;
import java.io.IOException;

public class F3
{
public static void main(String[] args)
{
// Define the file path and content to write
String fp = "aout.txt";
String con = "This is a sample text written using byte streams!";

FileOutputStream w = null;

try
{
// Initialize FileOutputStream with the file path
w = new FileOutputStream(fp);

// Convert the content string into bytes and write to file


byte[] b = con.getBytes();
w.write(b);

System.out.println("Content written to file successfully.");


}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
// Close the FileOutputStream
try
{
if (w != null)

CIC Sagi Rama Krishnam Raju Engineering College(A) 12


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

w.close();
}
catch (IOException e)
{
System.out.println("Failed to close file output stream: " + e.getMessage());
}
}
}
}

Reading:
import java.io.FileInputStream;
import java.io.IOException;

public class F4
{
public static void main(String[] args)
{
// Define the file path to read from
String fp = "aout.txt";

FileInputStream r = null;

try
{
// Initialize FileInputStream with the file path
r = new FileInputStream(fp);

// Read bytes from the file and print to console


int b;
while ((b = r.read()) != -1)
{
System.out.print((char) b); // Convert byte to char and print
}
}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
// Close the FileInputStream
try
{
if (r != null)
r.close();
}
catch (IOException e)
{

CIC Sagi Rama Krishnam Raju Engineering College(A) 13


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

System.out.println("Failed to close file input stream: " + e.getMessage());


}
}
}
}

Coping:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class F5
{
public static void main(String[] args)
{
// Source and destination file paths
String sf = "aout.txt";
String df = "ain.txt";

FileInputStream r = null;
FileOutputStream w = null;

try
{
// Open input and output streams for source and destination files
r = new FileInputStream(sf);
w = new FileOutputStream(df);

// Buffer to hold byte data


byte[] b = new byte[1024];
int c;

// Read from source and write to destination


while ((c = r.read(b)) != -1)
{
w.write(b, 0, c);
}

System.out.println("File copied successfully.");


}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
// Close input and output streams in the finally block to ensure closure

CIC Sagi Rama Krishnam Raju Engineering College(A) 14


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

try
{
if (r != null)
r.close();
if (w != null)
w.close();
}
catch (IOException e)
{
System.out.println("Failed to close file streams: " + e.getMessage());
}
}
}
}

************

CIC Sagi Rama Krishnam Raju Engineering College(A) 15


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Object Oriented Programming Through JAVA


[B23CS2103]
Unit-V
_______________________________________________________________________________________________________
SYLLABUS:
Java Database Connectivity: Introduction, Structure of JDBC, JDBC Architecture, Types of
JDBC Drivers, JAVA Database connection program for MySQL.
_______________________________________________________________________________________________________

JDBC (Java Database Connectivity)

Java Database Connectivity (JDBC) is a Java API that allows Java applications to interact
with databases in a seamless and standardized manner. By providing a set of classes and
interfaces, JDBC enables developers to connect to a database, execute SQL queries, and
retrieve or manipulate data programmatically.

Purpose of JDBC:

JDBC was introduced to address the need for a portable, database-independent solution for
Java applications to work with databases. It abstracts database-specific details and provides
a unified interface for all database interactions.

1. Facilitates Database Access for Java Applications:


o JDBC acts as a bridge between Java programs and databases.
o It allows Java developers to execute SQL commands such as SELECT, INSERT,
UPDATE, and DELETE directly from their programs.
o Simplifies the process of accessing and managing relational data.
2. Enables Portability:
o JDBC provides a database-independent API, meaning Java applications
written using JDBC can work with any database, provided the appropriate
driver is available.
o This makes Java programs portable across different database systems,
reducing vendor lock-in.

Key Features of JDBC:

1. Database and Platform Independence:


o JDBC abstracts the database-specific details, ensuring that applications are
not tied to a particular database or operating system.
2. Dynamic SQL Query Support:
o JDBC supports both static SQL (predefined queries) and dynamic SQL
(queries built at runtime).
3. Robust Error Handling:
o JDBC provides a structured mechanism to handle errors and exceptions that
may occur during database operations using SQLException.
4. Multiple Driver Support:
o JDBC supports a variety of driver types (e.g., JDBC-ODBC bridge, Thin driver),
making it versatile and compatible with a wide range of databases.
5. Scalability:

CIC Sagi Rama Krishnam Raju Engineering College(A) 1


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

o JDBC supports connection pooling, which improves performance by reusing


database connections instead of creating new ones for every operation.
6. Transactional Support:
o JDBC enables developers to manage transactions programmatically, ensuring
data consistency and integrity.

Use Cases of JDBC:

1. Web and Enterprise Applications:

JDBC is extensively used in web and enterprise applications where persistent data storage
and retrieval are essential. Examples include:

• E-commerce applications to store product and customer information.


• Banking systems to manage transactions and account details.

2. Dynamic Data-Driven Decisions:

Applications that require real-time data to make decisions can leverage JDBC to query
databases dynamically.

• For example, inventory management systems that update stock levels based on real-
time sales data.

3. Data Migration:

JDBC can be used for transferring data between different databases or exporting data to
external formats.

4. Reporting and Analytics:

JDBC enables data retrieval for creating custom reports and performing analytics.

Advantages of JDBC:

1. Ease of Use:
o JDBC simplifies the process of connecting to databases and executing queries
through a straightforward API.
2. Flexibility:
o With its support for multiple databases and dynamic queries, JDBC can handle a
variety of use cases.
3. Integration with Java Ecosystem:
o JDBC integrates seamlessly with other Java frameworks and technologies, such
as Hibernate, Spring, and Java EE.

Key Challenges of JDBC:

While JDBC is a powerful tool, developers may face challenges such as:

• Managing database connections effectively to avoid resource leaks.


• Writing boilerplate code for repetitive tasks (e.g., opening and closing connections).

CIC Sagi Rama Krishnam Raju Engineering College(A) 2


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

• Handling database-specific SQL syntax differences.

Real-World Example:

Suppose an online bookstore wants to display the details of all books in its catalog. Using
JDBC:

1. The Java application connects to the database.


2. Executes a query like SELECT * FROM books.
3. Retrieves and displays the result, enabling users to view the catalog.

In conclusion, JDBC is a cornerstone of Java's ability to handle database operations, making


it a critical tool for developers building data-driven applications. Let me know if you’d like
to dive deeper into any specific aspect!

Structure of JDBC

Fig: Structure of JDBC

Core Components:

1. Driver Manager: Manages database drivers and establishes connections.


2. Driver: Connects the Java application to the database. Drivers implement the
java.sql.Driver interface.
3. Connection: Represents a session with the database. Provides methods to create
statements.
4. Statement: Executes SQL queries (e.g., Statement, PreparedStatement,
CallableStatement).
5. ResultSet: Holds the data retrieved by executing SQL queries.
6. SQLException: Handles database access errors and exceptions.

Workflow:

1. Load the driver class.


2. Establish a connection using DriverManager.
3. Create a Statement object.
4. Execute SQL queries.
5. Process the ResultSet.
6. Close connections and resources.

CIC Sagi Rama Krishnam Raju Engineering College(A) 3


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

JDBC Architecture

There Are Two Architectures Of JDBC:

Two-Tier Architecture

1. Structure:
o Direct communication between client (user’s application) and the database
(data source).
o No intermediary layer.
2. How it works:
o User commands go directly to the database, and results are returned directly
to the user.
3. Example:
o A Java application directly querying a MySQL database using a JDBC driver.
4. Limitations:
o Harder to control access to data.
o Deployment changes require updates to every client.
o Performance issues with many clients.

Three-Tier Architecture

CIC Sagi Rama Krishnam Raju Engineering College(A) 4


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

1. Structure:
o Involves three layers:
▪ Client (user’s application).
▪ Middle Tier (services like business logic, API, or application server).
▪ Database (data source).
2. How it works:
o User commands are sent to the middle tier.
o The middle tier processes these commands and communicates with the
database.
o Results from the database are passed back through the middle tier to the
user.
3. Example:
o A Java application sends requests to an application server (middle tier),
which interacts with the database.
4. Advantages:
o Easier to manage and secure access to the database.
o Simplifies updates and deployment (changes are centralized in the middle
tier).
o Better performance when handling multiple users.

1. Application Layer:

Role: This is the topmost layer and represents the Java program written by the developer.
It contains the application logic that interacts with the database to perform tasks like data
retrieval, updates, and deletions.

Responsibilities:

CIC Sagi Rama Krishnam Raju Engineering College(A) 5


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

• Sending SQL queries to the database through the JDBC API.


• Processing the data received (via ResultSet) from the database.

Example: A Java application that retrieves product details from a database for an e-
commerce platform.

2. JDBC API Layer:

Role: This layer provides a standardized set of interfaces and classes in the java.sql package.
It acts as a bridge between the application and the database-specific JDBC drivers.

Responsibilities:

• Facilitating communication between the Java application and the JDBC driver.
• Abstracting database-specific details from the application, making it independent of
the database.

Key Components:

• DriverManager: Manages database drivers and provides connections.


• Connection: Represents the session with the database.
• Statement: Executes SQL queries.
• ResultSet: Retrieves data from query results.

Example Classes: DriverManager, Statement, PreparedStatement, CallableStatement.

3. JDBC Driver Layer:

Role: This layer consists of the JDBC drivers that convert API calls from the application
into database-specific calls. Each database system requires its own JDBC driver.

Responsibilities:

• Translating JDBC API methods into SQL commands understood by the database.
• Establishing a connection with the database.

Driver Types:

• JDBC-ODBC Bridge Driver.


• Native API Driver.
• Network Protocol Driver.
• Thin Driver (used for database systems like MySQL and Oracle).

Example:

• For MySQL: com.mysql.cj.jdbc.Driver.


• For Oracle: oracle.jdbc.OracleDriver.

4. Database Layer:

CIC Sagi Rama Krishnam Raju Engineering College(A) 6


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Role: This is the actual database system where the data resides. It processes the SQL
queries sent by the driver and returns the results back to the application.

Responsibilities:

• Storing and managing data in tables, views, or other structures.


• Executing queries like SELECT, INSERT, UPDATE, and DELETE.
• Providing transaction support to ensure data integrity.

Examples of Databases:

• Relational Databases: MySQL, Oracle, SQL Server, PostgreSQL.


• Non-Relational Databases (can be accessed via alternative drivers): MongoDB,
Cassandra.

Workflow of JDBC Architecture

1. Application Layer:

• The user interacts with the Java application, which sends a request to perform an
operation on the database (e.g., retrieve employee records).
• Example: The Java application contains a query like:

SELECT * FROM employees;

2. JDBC API Layer:

• The API receives this query and interacts with the DriverManager to establish a
connection to the database.
• Example: The application uses the DriverManager.getConnection() method.

3. JDBC Driver Layer:

• The JDBC driver converts the standardized API calls into database-specific calls.
• It communicates with the database using the appropriate protocol (e.g., SQL over
TCP/IP for MySQL).

4. Database Layer:

• The database executes the query and sends the result back to the driver.
• Example: A MySQL database fetches the requested rows from the employees table.

5. Reverse Communication:

• The driver converts the database-specific results into a format compatible with the
JDBC API (e.g., ResultSet).
• The Java application processes the ResultSet and displays the data to the user.

CIC Sagi Rama Krishnam Raju Engineering College(A) 7


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Advantages of This Architecture

• Modularity: The layers are independent, making it easier to replace or update a


specific layer without affecting others.
• Portability: Applications can work with different databases by simply changing the
driver without altering the application logic.
• Standardization: The JDBC API provides a consistent interface for database
operations across various databases.
• Scalability: JDBC supports multiple concurrent database connections, making it
suitable for enterprise applications.

Types of JDBC Drivers

Thin
Driver

Type 1: JDBC-ODBC Bridge Driver

This driver acts as a bridge between JDBC and ODBC. It converts JDBC calls to ODBC calls,
which are then sent to the database. It requires an ODBC driver to be configured on the
system. This type is now deprecated and not recommended for modern applications.

Advantages Disadvantages
- Platform-dependent; requires ODBC driver
- Easy to set up and use for beginners.
setup.
- Provides access to any ODBC-compliant - Poor performance due to multiple layers of
database. translation.
- Deprecated and no longer supported in Java 8
and beyond.

CIC Sagi Rama Krishnam Raju Engineering College(A) 8


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Type 2: Native API Driver

This driver uses database vendor-specific native libraries to convert JDBC calls into
database-specific calls. The native libraries must be installed on the client machine. While
it offers better performance than Type 1, it is not portable due to its dependency on
platform-specific native code.

Advantages Disadvantages
- Better performance than Type 1 due - Platform-dependent; requires database-specific
to fewer layers. native libraries installed.
- Deployment and maintenance are challenging on
- Supports database-specific features.
multiple platforms.
- Not portable; tied to the specific database and
operating system.

Type 3: Network Protocol Driver

This driver communicates with the database through a middleware server. The middleware
translates the JDBC calls into database-specific protocol calls. It is platform-independent
and ideal for web-based applications where remote database access is required.

Advantages Disadvantages
- Platform-independent; no client-side - Requires additional middleware, increasing
dependencies. setup complexity.
- Adds latency due to communication with
- Supports remote access to databases.
middleware.
- Middleware can handle connection - Maintenance overhead for middleware
pooling and caching. server.

Type 4: Thin Driver

This driver directly converts JDBC calls into database-specific network protocol calls. It is
written entirely in Java, making it platform-independent. No additional software or
middleware is required, making it the most commonly used driver for modern applications.

Advantages Disadvantages
- Fast and lightweight due to direct - Database-specific; a separate driver is required
communication. for each database type.
- Platform-independent; works on any - May lack advanced features compared to
system with Java. middleware-based solutions.
- No additional software or middleware
needed.

CIC Sagi Rama Krishnam Raju Engineering College(A) 9


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Comparison Table:

Platform
Type Translation Layer Performance Use Case Example
Independence
JDBC → ODBC → Microsoft Access with
Type 1 No Slow
Database ODBC driver
JDBC → Native API Faster than Oracle with OCI
Type 2 No
→ Database Type 1 driver
JDBC →
Type 3 Middleware → Yes Moderate IDS Server
Database
JDBC → Database MySQL Connector/J,
Type 4 Yes Fastest
(Direct) PostgreSQL

Java Database Connection Program for MySQL

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

public class MySQLConnectionExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";

try {
// Step 1: Load the MySQL driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish a connection


Connection connection = DriverManager.getConnection(url, username,
password);

System.out.println("Connected to the database!");

// Step 3: Create a Statement object


Statement statement = connection.createStatement();

// Step 4: Execute a query


String query = "SELECT * FROM your_table";
ResultSet resultSet = statement.executeQuery(query);

// Step 5: Process the ResultSet


while (resultSet.next()) {
System.out.println("Column1: " + resultSet.getString("column1"));
System.out.println("Column2: " + resultSet.getInt("column2"));
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 10


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

// Step 6: Close the connection


resultSet.close();
statement.close();
connection.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation of the Program:
1. Load the Driver:
• Class.forName("com.mysql.cj.jdbc.Driver"); loads the MySQL driver into memory.
2. Establish Connection:
• DriverManager.getConnection() creates a session with the database.
3. Create Statement:
• A Statement object is used to send SQL queries to the database.
4. Execute Query:
• executeQuery() runs the SQL query and returns a ResultSet.
5. Process ResultSet:
• The data from the database is iterated and displayed.
6. Close Resources:
• Ensures connections and resources are properly released.

STEPS FOR WRITING A JDBC PROGRAM

Step 1: Register the Driver

To connect to the database, you first need to load or register the driver.

Syntax Options:

Class.forName("url");
DriverManager.registerDriver(new Driver("url"));
System.setProperty("url");

Step 2: Establish the Database Connection

Use the DriverManager class to create a connection to the database.

Syntax:

Connection con = DriverManager.getConnection("url", "username", "password");

Step 3: Prepare the SQL Statement

Create an SQL statement using one of these interfaces:

• Statement: For simple SQL queries.


• PreparedStatement: For parameterized queries.
• CallableStatement: For stored procedures.

CIC Sagi Rama Krishnam Raju Engineering College(A) 11


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Syntax:

Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement("sql query");
CallableStatement cs = con.prepareCall("stored procedure");

Step 4: Execute the SQL Statement

Execute the query using appropriate methods:

• execute(): For general execution.


• executeQuery(): For SELECT statements.
• executeUpdate(): For INSERT, UPDATE, or DELETE.

Syntax:

boolean b = st.execute("sql query");


int i = st.executeUpdate("INSERT/DELETE/UPDATE query");
ResultSet rs = st.executeQuery("SELECT query");

Step 5: Retrieve the Results

Use the ResultSet interface to handle results of a SELECT query. The ResultSet maintains a
cursor to traverse rows.

Syntax:

ResultSet rs = st.executeQuery("SELECT * FROM table_name");


while (rs.next()) {
// Access data using rs.getXXX(columnIndex);
}

Step 6: Close the Connection

Free up resources by closing the connection.

Syntax:

con.close();
st.close();
rs.close();

JDBC Classes, Interfaces, and Methods Table

Class/Interface Purpose Key Methods


Manages a list of database
getConnection(String url, String user,
DriverManager drivers and establishes
String password)
connections.
Represents a connection to createStatement(),
Connection
the database. prepareStatement(String sql), close()

CIC Sagi Rama Krishnam Raju Engineering College(A) 12


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Class/Interface Purpose Key Methods


execute(String sql),
Used to execute static SQL
Statement executeQuery(String sql),
queries.
executeUpdate(String sql)
Used to execute
execute(), executeQuery(),
PreparedStatement parameterized SQL queries
executeUpdate(), setXXX(int, value)
for efficiency and security.
execute(), executeQuery(),
Executes stored procedures
CallableStatement executeUpdate(),
in the database.
registerOutParameter()
Holds data retrieved by
next(), getXXX(int/columnLabel),
ResultSet SELECT queries and allows
close(), wasNull()
navigation of results.
Handles database-related getMessage(), getErrorCode(),
SQLException
errors and exceptions. getSQLState(), printStackTrace()

JDBC Programs for Connection, Insert, Update, Delete, and Select

Below are the programs to demonstrate various JDBC operations, each with an appropriate
heading.

To set the classpath of jar file use at CMD >set classpath=


C:\Users\kdvpk\OneDrive\Desktop\Java 24_25 AIML\programs\mysql-connector-j-
9.1.0.jar;

Establishing a Connection

import java.sql.*;

public class ConnectionDemo {


public static void main(String[] args) {
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish the connection


Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/srinu", "root", "");

// Step 3: Print success message


System.out.println("Connection established successfully!");

// Step 4: Close the connection


con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 13


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

Inserting Data
import java.sql.*;

public class InsertDemo {


public static void main(String[] args) {
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish the connection


Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/srinu", "root", "");

// Step 3: Create SQL statement


Statement st = con.createStatement();
int rowsInserted = st.executeUpdate("INSERT INTO student VALUES (501,
'Mahima')");

// Step 4: Check and print the result


if (rowsInserted > 0) {
System.out.println("Record inserted successfully!");
}

// Step 5: Close the connection


st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Updating Data

import java.sql.*;

public class UpdateDemo {


public static void main(String[] args) {
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish the connection


Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/srinu", "root", "");

// Step 3: Create SQL statement


Statement st = con.createStatement();
int rowsUpdated = st.executeUpdate("UPDATE student SET sname='Pavan'
WHERE sid=501");

CIC Sagi Rama Krishnam Raju Engineering College(A) 14


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

// Step 4: Check and print the result


if (rowsUpdated > 0) {
System.out.println("Record updated successfully!");
}

// Step 5: Close the connection


st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Deleting Data

import java.sql.*;

public class DeleteDemo {


public static void main(String[] args) {
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish the connection


Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/srinu", "root", "");

// Step 3: Create SQL statement


Statement st = con.createStatement();
int rowsDeleted = st.executeUpdate("DELETE FROM student WHERE
sid=501");

// Step 4: Check and print the result


if (rowsDeleted > 0) {
System.out.println("Record deleted successfully!");
}

// Step 5: Close the connection


st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Selecting Data
import java.sql.*;

CIC Sagi Rama Krishnam Raju Engineering College(A) 15


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.Neelima

public class SelectDemo {


public static void main(String[] args) {
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish the connection


Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/srinu", "root", "");

// Step 3: Create SQL statement


Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM student");

// Step 4: Process the result set


while (rs.next()) {
int sid = rs.getInt(1);
String sname = rs.getString(2);
System.out.println("Student ID: " + sid + ", Student Name: " + sname);
}

// Step 5: Close the resources


rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

************

CIC Sagi Rama Krishnam Raju Engineering College(A) 16

You might also like