Unit 5 - Interacting With Databases
Unit 5 - Interacting With Databases
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.
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.
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:
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.
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.
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)
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
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.
Advantage:
● Better performance than all other drivers.
● No software is required at client side or server side.
Disadvantage:
● Drivers depend on the Database.
Class.forName("com.mysql.jdbc.Driver");
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.
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
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", "");
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 > ?
Example:
java
ps.setInt(1, 100000); // Replace the first '?' with 100000
For INSERT/UPDATE/DELETE:
java
int rowsAffected = ps.executeUpdate();
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.
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).
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)
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.
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.
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 Driver Manager is the backbone of the JDBC architecture, responsible for managing the
database drivers and establishing connections between Java applications and various databases.
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.