0% found this document useful (0 votes)
18 views

Unit 5 - Interacting With Databases

Uploaded by

Sujal Sonawane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit 5 - Interacting With Databases

Uploaded by

Sujal Sonawane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Advanced Java Programming

Unit 5 : Interacting with Databases

Java as Database Frontend


Platform Independence: Java is a "Write Once Run Everywhere" language, allowing applications
to be deployed on any system with a Java Virtual Machine (JVM) without recompilation.

CostEffective Client Solutions: Traditional fat clients (Windows, Macintosh, Unix) can cost
between $10,000 to $15,000 per installation. In contrast, Javabased thin clients require minimal
hardware resources and are expected to cost around $70 per seat.

Significant Savings: Transitioning from 10,000 fat clients to thin clients can save corporations up
to $100 million annually.

IndustrialStrength DBMS: Popular database management systems (DBMS) include Oracle, DB2,
and Sybase.

JDBC Development: In the late 1990s, Sun Microsystems created JDBC (Java Database
Connectivity) to enable Java developers to write high level code that accesses various DBMS.

JDBC Driver Specification: The JDBC driver is not a single driver but a specification detailing
the functionalities required for JDBC drivers. DBMS manufacturers were encouraged to develop
compliant drivers.

Translation of Messages: JDBC drivers serve as translators, converting proprietary DBMS


messages to JDBC API messages and vice versa, allowing Java programs to interact with
databases using high level Java data objects.

Facilitated Java Database Access: The JDBC API enables Java programmers to write routines
that can interact with DBMS, transforming high level Java data objects into low level messages
for database processing.

Database client server methodology


Common DBMS: Relational databases are the most widely used type of database management
system (DBMS).

Separation of Data: A defining feature of relational databases is the strict separation between
physical and logical data. Data is accessed via a logical model rather than relying on physical
storage locations.
Advanced Java Programming

Integrity and Relationships: Relational databases enable the definition of relationships and
integrity rules between different data sets.

Development History: The relational database model was developed by E.F. Codd at the IBM
San Jose Research Lab in the 1970s.

SQL Introduction: Alongside the relational model, SQL (Structured Query Language) was also
developed at IBM. SQL is the language used to interact with a DBMS.

Functionality of SQL:
● Data Access: SQL allows data access without needing to specify physical access
methods.
● Record Retrieval: It enables data retrieval in the form of sets of records.
● Complex Computations: SQL can perform complex computations on the data, enhancing
its utility for database operations.

Software Architecture
TwoTier ClientServer Architecture
Definition: The first generation of client-server architecture, known as two-tiered architecture,
consists of two active components: the client and the server.

Functionality:
● The client requests data and handles user interface presentations, including graphics and
data entry validation.
● The server delivers data and performs all data processing through a central DBMS.
● Network connectivity typically links the client and server, though both may reside on the
same hardware.
● Example: Airline seat reservation applications that connect to a central DBMS for data
requests, inserts, or modifications.

Architecture Layers:
● Application Layer: Includes JDBC drivers, business logic, and user interfaces.
● Database Layer: Comprises the RDBMS server.

Advantages:
● Simple design.
● Client Side scripting offloads processing from the server.
Advanced Java Programming

Drawbacks:

● Fat client architecture, leading to heavier clients.


● Inflexibility in handling changes across both tiers.

ThreeTier ClientServer Architecture


Definition: A more recent architectural design that includes a third tier, separating application
logic from the database and client.

Functionality:
The middle tier contains most of the business logic, allowing modifications without changing
client or database logic when business rules change.

Architecture Layers:
● Presentation Layer: User interface.
● Business Logic Layer: Middleware containing business rules.
● Data Management Layer: Database management.

Advantages:
● Flexibility: Changes can be made to one part without affecting others.
● Database Independence: Can connect to different databases without code changes.
● Specialization: Allows distinct management of presentation, business logic, and data.
● Caching: Can cache queries for improved performance.
● Security: Can implement proxies and firewalls for enhanced security.

Drawbacks:
● Higher complexity due to the additional tier.
● Increased maintenance requirements.
● Potentially lower network efficiency.
● More components to configure and purchase.

JDBC (Java Database Connectivity)


Definition: JDBC stands for Java Database Connectivity, a specification and API for connecting
Java applications and applets to data sources such as databases.
Main Components:

● Specification: Defines how Java applications interact with data sources.


● API for Using JDBC Drivers: Provides methods to connect to and query databases.
● API for Creating JDBC Drivers: Allows for the development of lowlevel drivers that
handle the actual data transactions.
Advanced Java Programming

Based on CLI: JDBC is built on the X/Open SQL Call Level Interface (CLI), which defines
clientserver interactions for databases.
HighLevel Interface: JDBC abstracts databasespecific syntax, so developers can write code that
works across different databases without worrying about specific commands.
Java Package: JDBC functions similarly to other Java packages (like java.awt) and is
included in the java.sql package.
Driver Download with Applets: JDBC drivers can be downloaded along with applets, avoiding
the need for preinstallation on the client side.
History: The JDBC project started in January 1996, and the specification was finalized in June
1996.
Industry Adoption: JDBC has been endorsed by numerous database vendors, including:

● Borland International
● IBM's DB2
● Oracle Corporation
● Sybase, Inc.
● WebLogic, Inc., and many more.

Flexibility: JDBC's flexibility allows developers to work with both legacy and modern
databases, making it a powerful tool for a wide range of applications.

JDBC Structure
Two Dimensional Structure: JDBC is designed to separate lowlevel programming from the
highlevel application interface.

● LowLevel Programming: This is handled by the JDBC driver, responsible for


connecting to the data source or database.
● HighLevel Application Interface: Allows developers to write code that interacts with
databases without needing to understand the lowlevel specifics.

PreBuilt JDBC Drivers: Database and thirdparty vendors provide prebuilt JDBC drivers for
connecting to different databases, whether local or remote.
Flexibility of JDBC Drivers: JDBC drivers are designed to connect to various types of data
sources, including local data sources or remote database servers.
DBMS Independent Interface: The main goal of JDBC is to create a database management
system (DBMS)independent interface, offering a "generic SQL database access framework" that
provides uniform access to different data sources.
Single Database Interface for Developers: Developers only need to write one database
interface using JDBC, which can then access multiple data sources without additional
modification.
Advanced Java Programming

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
● JDBC-ODBC bridge driver
● NativeAPI driver (partially java driver)
● Network Protocol driver (fully java driver)
● Thin driver (fully java driver)

1) JDBCODBC bridge driver


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

In Java 8, the JDBCODBC Bridge has been removed.


Oracle does not support the JDBCODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBCODBC Bridge.

Advantages:
● easy to use.
● can be easily connected to any database.
Disadvantages:
● Performance degraded because JDBC method call is converted into the ODBC function
calls.
Advanced Java Programming

● The ODBC driver needs to be installed on the client machine.

2) NativeAPI driver
The Native API driver uses the clientside libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:
● performance upgraded than JDBCODBC bridge driver.
Disadvantage:
● The Native driver needs to be installed on the each client machine.
● The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


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

Network Protocol driver


Advantage:
● No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
● Network support is required on client machine.
● Requires database-specific coding to be done in the middle tier.
● Maintenance of Network Protocol driver becomes costly because it requires
databasespecific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendorspecific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advanced Java Programming

Advantage:
● Better performance than all other drivers.
● No software is required at client side or server side.
Disadvantage:
● Drivers depend on the Database.

1. Load the JDBC Driver:


Before the Java application connects to the database, the JDBC driver must be loaded. This is
done using the Class.forName() method, which loads the driver class into memory. For instance,
the JDBCODBC Bridge driver (sun.jdbc.odbc.JdbcOdbcDriver) is commonly used.

Class.forName("com.mysql.jdbc.Driver");

2. Define and Establish the Connection:


After loading the JDBC driver, the application needs to establish a connection to the database.
This is done using the DriverManager.getConnection() method, which takes in the database
URL, user ID, and password. The DriverManager is a part of Java's java.sql package and is
responsible for managing database connections.
Advanced Java Programming

The connection URL follows the format <protocol>:<subprotocol>:<dsnname>. For example, in


jdbc:odbc:customer, the protocol is jdbc, the subprotocol is odbc, and customer is the Data
Source Name (DSN) for the database.

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

3. Create a Statement Object:


Once the connection is established, the application creates a Statement object. This object is used
to send SQL queries to the database. The createStatement() method of the Connection interface
is used for this purpose. The Statement object allows for query execution and interacting with the
database.

Statement stmt = con.createStatement();

4. Execute a Query:
After creating the Statement object, the SQL query is executed. The executeQuery() method is
used for this, and it returns a ResultSet object. The ResultSet object contains the data retrieved
from the database as a result of the query. For instance, when selecting data from a table, the
ResultSet will hold all the rows and columns returned by the query.

ResultSet rs = stmt.executeQuery("select * from emp");

5. Process the Results:


The ResultSet object contains methods to interact with the query result. The next() method
moves the cursor to the next row of the result set, allowing the application to process each row
one at a time. The getDatatype() methods, where Datatype can be types like String, Int, etc., are
used to read the values from the current row in the result set. For example, getString() reads a
string value from a specified column, and getInt() reads an integer value from another column.

while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));

6. Close the Connection:


After the query has been executed and the results processed, it is important to close the
connection to the database. The close() method is used for this, which releases the database and
system resources that were tied to the connection.
The Statement object is also closed after its usage, preventing further interaction with the
database through that particular object.

con.close();
Advanced Java Programming

Example:
import java.sql.*;

class MysqlCon {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Steps: https://www.javatpoint.com/example-to-connect-to-the-mysql-database

Statement Object
The Statement object in JDBC is a core object used to execute SQL queries immediately without
compiling them first. It provides three main methods for executing different types of queries:
1. executeQuery():
This method is used to execute SQL queries that return data, such as the SELECT statement.
It returns a ResultSet object, which contains the rows, columns, and metadata of the data
requested by the query.
The method's signature is:
● ResultSet executeQuery(String query)
Usage: Primarily for executing SELECT queries that retrieve data from a database.
Advanced Java Programming

2. executeUpdate():
This method is used to execute SQL queries that modify data, such as INSERT, DELETE, or
UPDATE statements.
It returns an integer that indicates the number of rows affected by the query.
The method's signature is:
● int executeUpdate(String query)
Usage: For executing queries that update the database, like inserting new records or deleting
existing ones.

Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

class AccountManager {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/accounts",
"root", "");

// Prepare the SQL INSERT statement


String insertSQL = "INSERT INTO account (account_id, balance) VALUES (?, ?)";
PreparedStatement ps = con.prepareStatement(insertSQL);
ps.setInt(1, 104); // Set account_id
ps.setFloat(2, 1200.0f); // Set balance

// Execute the INSERT statement


int rowsAffected = ps.executeUpdate();
System.out.println("Rows affected: " + rowsAffected);

// Close the connection


ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advanced Java Programming

Output:

3. execute():
This method can execute any SQL statement, including those that may return multiple results
(i.e., both result sets and update counts).
It returns a boolean value:
● true if the first result is a ResultSet,
● false if the result is an update count or there are no results.
The method's signature is:
● public boolean execute(String sql)
In case the SQL query returns multiple results (both ResultSet and update counts), additional
methods like getResultSet(), getUpdateCount(), and getMoreResults() must be used to retrieve
and process them.
● getResultSet() retrieves the current result set if available.
● getUpdateCount() retrieves the update count, i.e., the number of rows affected by the
SQL statement.
● getMoreResults() moves to any subsequent results if there are multiple result sets or
update counts.
Summary of Method Signatures:
● ResultSet getResultSet() – Retrieves the current ResultSet after calling execute().
● int getUpdateCount() – Retrieves the update count after calling execute().
● boolean getMoreResults() – Moves to the next result if there are multiple results.
Example Use Cases:
● executeQuery(): For retrieving data using SELECT statements.
● executeUpdate(): For modifying data using INSERT, DELETE, or UPDATE statements.
● execute(): For situations where multiple result sets or update counts are expected from a
single query.
Advanced Java Programming

PreparedStatement
Precompile SQL queries for execution efficiency.

Benefits:
Reduces overhead for queries executed multiple times.
Helps prevent SQL injection attacks.

Creating a PreparedStatement
1. Define the SQL Query:
Use placeholders (question marks) for dynamic values.
Example:
sql
SELECT FROM nation WHERE population > ?

2. Prepare the Statement:


Use the prepareStatement() method from the Connection object.
Example:
java
PreparedStatement ps = con.prepareStatement(query);

Setting Parameter Values


Use setDatatype() methods to assign values to placeholders.
Commonly Used Methods:
setInt(int index, int value)
setString(int index, String value)
setDouble(int index, double value)
setDate(int index, Date value)

Example:
java
ps.setInt(1, 100000); // Replace the first '?' with 100000

Executing the PreparedStatement


Use the appropriate execute method based on the query type:
For SELECT queries:
java
ResultSet rs = ps.executeQuery();
Advanced Java Programming

For INSERT/UPDATE/DELETE:
java
int rowsAffected = ps.executeUpdate();

For general queries:


java
boolean result = ps.execute();

Example Code
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

class StudentData {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/stud",
"root", "");
PreparedStatement ps = con.prepareStatement("SELECT * FROM student WHERE
Marks > ?");
ps.setInt(1, 70);
ResultSet rs = ps.executeQuery();
System.out.println("Students having marks > 70 are:");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advanced Java Programming

Output

Summary
PreparedStatement enhances performance for repeated queries.
Prevents SQL injection and ensures cleaner code.
Use set methods to bind parameters and execute to run the query.

CallableStatement

Overview of CallableStatement
- Purpose: Used to call stored procedures in a JDBC application.
- Stored Procedures: Precompiled blocks of code stored in the database that can be executed by
name. They can be written in various languages like PL/SQL or Transact-SQL.

Types of Parameters
1. IN Parameters:
- Used to pass values to the stored procedure.
- Assigned using setXxx() methods.

2. OUT Parameters:
- Used to retrieve values from the stored procedure.
- Must be registered with registerOutParameter() method and accessed using getXxx()
methods.

3. INOUT Parameters:
- Used to both send and receive values from the stored procedure.

Example of a Stored Procedure


Advanced Java Programming

sql
CREATE PROCEDURE sp_interest
(id IN INTEGER,
bal IN OUT FLOAT) IS
BEGIN
SELECT balance INTO bal
FROM account
WHERE account_id = id;
bal := bal + bal *0.03;
UPDATE account SET balance = bal WHERE account_id = id;
END;

- Parameters:
- id: IN parameter (input).
- bal: INOUT parameter (input and output).

Using CallableStatement in Java


1. Establishing Connection: First, create a connection to the database.

2. Prepare the CallableStatement:


- Use prepareCall() method of the Connection object to prepare the stored procedure call.
- Example:
java
CallableStatement cs = con.prepareCall("{call sp_interest(?, ?)}");

3. Set IN Parameters:
- Use the setXxx() methods to set values for IN parameters.
- Example:
java
cs.setInt(1, accountId); // Set the IN parameter
cs.setFloat(2, initialBalance); // Set the INOUT parameter (initial value)

4. Register OUT Parameters:


- Use registerOutParameter() for any OUT parameters.
- Example:
java
cs.registerOutParameter(2, java.sql.Types.FLOAT); // Register the OUT parameter
Advanced Java Programming

5. Execute the CallableStatement:


- Call the stored procedure using execute() method.
- Example:
java
cs.execute();

6. Retrieve OUT Parameters:


- Use getDatatype() methods to retrieve the values of OUT parameters after execution.
- Example:
java
float updatedBalance = cs.getFloat(2); // Get the updated balance

Example Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.CallableStatement;

class InterestCalculator {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/accounts",
"root", "");
CallableStatement cs = con.prepareCall("{call sp_interest(?, ?)}");
cs.setInt(1, 101); // Example account ID
cs.setFloat(2, 1000.0f); // Initial balance
cs.registerOutParameter(2, java.sql.Types.FLOAT);
cs.execute();
float updatedBalance = cs.getFloat(2);
System.out.println("Updated Balance: " + updatedBalance);
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advanced Java Programming

Output:

Summary
- CallableStatement enables calling stored procedures from Java applications.
- Supports IN, OUT, and INOUT parameters for flexible data handling.
- Use prepareCall(), setXxx(), registerOutParameter(), and getXxx() methods for execution and
retrieval.

Important Points to Remember


OCI stands for Oracle Call Interface. It is a set of low-level APIs provided by Oracle that allows
C and C++ applications to communicate with Oracle databases. OCI provides a powerful way to
execute SQL statements and manage database operations directly from application code,
enabling efficient interaction with Oracle database features.

The java.sql package is fundamental for basic JDBC operations, while the javax.sql package
builds on this functionality, offering additional features like connection pooling, data source
management, and distributed transactions.

A DataSource is an interface in the javax.sql package that provides an alternative way to


establish a connection to a database. It offers more advanced features than DriverManager, such
as connection pooling and distributed transactions.

DriverManager is a class in the java.sql package that manages a list of database drivers and
establishes connections to a database.

JNDI is a Java API that provides naming and directory functionality to allow applications to look
up data sources and other resources by a logical name, facilitating easier resource management.

The DataSource implementation is provided by the driver vendor to facilitate the creation of
database connections, often supporting advanced features like connection pooling and distributed
transactions.
Advanced Java Programming

The PreparedStatement interface is a sub-interface of the Statement interface that allows the
execution of precompiled SQL queries with input parameters, enhancing performance and
security.

The javax.sql.ConnectionPoolDataSource interface provides a factory for creating


PooledConnection objects, allowing applications to manage and reuse database connections
efficiently.

The javax.sql.ConnectionPoolDataSource interface is designed to provide an object that manages


connection pools, facilitating the efficient allocation and reuse of database connections in
applications.

The MicrosoftODBCForOracle driver is required for ODBC connectivity to Oracle databases,


enabling applications to interact with Oracle using the ODBC protocol.

The Driver Manager is the backbone of the JDBC architecture, responsible for managing the
database drivers and establishing connections between Java applications and various databases.

The SQL.Connection interface defines five transaction isolation levels:


TRANSACTION_NONE, TRANSACTION_READ_UNCOMMITTED,
TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, and
TRANSACTION_SERIALIZABLE, allowing control over the visibility of changes made by
transactions.

Type 3 architecture, known as JDBC-Net pure Java, uses a middleware server to convert JDBC
calls into the database-specific protocol, allowing for a pure Java implementation that can
connect to various databases over a network.

Type IV JDBC driver is also known as Native Protocol Pure-Java Driver, as it converts JDBC
calls directly into the database-specific protocol without the need for middleware, allowing for
efficient and direct database communication

The Permission class is part of the java.security package, which provides the framework for
managing security permissions in Java applications.

All the Best!


With Regards
Darshan Sir and Team V2V

You might also like