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

module-3 notes

The document provides an overview of Relational Database Management Systems (RDBMS), detailing its history, features, and advantages, as well as the differences between DBMS and RDBMS. It also introduces the Call Level Interface (CLI) in JDBC, explaining its functions, usage, and benefits for executing stored procedures in Java applications. Additionally, it covers JDBC architecture, its applications, and the JDBC 4.0 packages, emphasizing the importance of JDBC for database connectivity in Java programming.

Uploaded by

SyedaFatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

module-3 notes

The document provides an overview of Relational Database Management Systems (RDBMS), detailing its history, features, and advantages, as well as the differences between DBMS and RDBMS. It also introduces the Call Level Interface (CLI) in JDBC, explaining its functions, usage, and benefits for executing stored procedures in Java applications. Additionally, it covers JDBC architecture, its applications, and the JDBC 4.0 packages, emphasizing the importance of JDBC for database connectivity in Java programming.

Uploaded by

SyedaFatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

MODULE-3:

JDBC

3.1.Overview of RDBMS:
RDBMS stands for Relational Database Management Systems. A database is an
organized collection of data stored in a computer system and usually controlled by a
database management system (DBMS). The data in common databases is modeled in tables,
making querying and processing efficient.
What is RDBMS?
RDBMS stands for Relational Database Management Systems. It is a program that allows
us to create, delete, and update a relational database. A Relational Database is a database
system that stores and retrieves data in a tabular format organized in the form of rows and
columns. It is a smaller subset of DBMS which was designed by E.F Codd in the 1970s.
The major DBMSs like SQL, My-SQL, and ORACLE are all based on the principles of
relational DBMS.
Relational DBMS owes its foundation to the fact that the values of each table are related to
others. It has the capability to handle larger magnitudes of data and simulate queries easily.

Relational Database Management Systems maintains data integrity by simulating the


following features:
 Entity Integrity: No two records of the database table can be completely duplicate.
 Referential Integrity: Only the rows of those tables can be deleted which are not used
by other tables. Otherwise, it may lead to data inconsistency.
 User-defined Integrity: Rules defined by the users based on confidentiality and access.
 Domain integrity: The columns of the database tables are enclosed within some
structured limits, based on default values, type of data or ranges.

RDBMS History
The history of Relational Database Management Systems (RDBMS) starts in the 1970s
with E F. Codd’s work at IBM. Codd introduced the concept of relational databases in 1970
that use of SQL (Structured Query Language) for querying data. This model revolutionized
data management by emphasizing data integrity and reducing redundancy. In the 1980s,
commercial RDBMS products such as Oracle, IBM DB2, and Microsoft SQL Server
emerged, making relational databases the industry standard for data management. Over the
decades, RDBMS technology has continued to evolve, incorporating advancements in
scalability, performance, and support for complex queries, cementing its role as a
cornerstone of modern database management.
What is a Database Table?
A table is a collection of related data in an organized manner in the form of rows and
columns. It is an organized arrangement of data and information in tabular
form containing rows and columns, making it easier to understand and compare data. Here
is the pictorial representation of the table and its different components containing the data
about different students that is ID, name, Age, and course.

Database Table
Features of RDBMS
 Data must be stored in tabular form in DB file, that is, it should be organized in the
form of rows and columns.
 Each row of table is called record/tuple . Collection of such records is known as the
cardinality of the table
 Each column of the table is called an attribute/field. Collection of such columns is
called the arity of the table.
 No two records of the DB table can be same. Data duplicity is therefore avoided by
using a candidate key. Candidate Key is a minimum set of attributes required to identify
each record uniquely.
 Tables are related to each other with the help for foreign keys.
 Database tables also allow NULL values, that is if the values of any of the element of
the table are not filled or are missing, it becomes a NULL value, which is not equivalent
to zero. (NOTE: Primary key cannot have a NULL value).

How Relational Database Model Work?


The relational database, created by IBM’s E.F. Codd in the 1970s, enables any table to be
associated to another table by means of a common attribute. Codd suggested a change to a
data model where data is stored, accessed, and related in tables without restructuring the
tables that hold them in place of hierarchical structures .
Each spreadsheet in the relational database model is a table that contains data, which is
shown as rows (records or tuples) and columns (attributes).
A data type is specified by an attribute (column), and the value of that particular data type
is contained in each record (or row). A primary key is an attribute found in all tables in a
relational database that serves as a unique row identifier. Let’s take an example.
Example: The following table STUDENT consists of three columns Roll Number, Name,
Section and four records of students 1, 2, 3 and 4 respectively. The records can’t be
completely same, the Roll Number acts as a candidate key which separates records.

Roll number Name Section

1 Ishita A

2 Yash B

3 Ishita A

4 Mallika C

Uses of RDBMS
 RDBMS is used in Customer Relationship Management.
 It is used in Online Retail Platforms.
 It is used in Hospital Management Systems.
 It is used in Business Intelligence .
 It is used in Data Warehousing
SQL Query in RDBMS
Creating a Table
Syntax:
CREATE TABLE table_name ( column1_name datatype constraint, column2_name
datatype constraint);
Example:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName
VARCHAR(50), LastName VARCHAR(50), BirthDate DATE, Salary DECIMAL(10, 2) );
2. Inserting Data into a Table
Syntax:
INSERT INTO table_name (column1_name, column2_name, …) VALUES (value1,
value2, …);
Example:
INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, Salary)
VALUES (1, ‘John’, ‘Doe’, ‘1985-06-15’, 55000.00);
3. Querying Data (SELECT)
Syntax:
SELECT column1_name, column2_name, … FROM table_name WHERE condition;
Example:
SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > 50000;
4. Deleting Data from a Table
Syntax:
DELETE FROM table_name WHERE condition;
Example:
DELETE FROM Employees WHERE EmployeeID = 1;

5. . Dropping a Table
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Employees;
Advantages of RDBMS
 Easy to Manage: Each table can be independently manipulated without affecting
others.
 Security: It is more secure consisting of multiple levels of security. Access of data
shared can be limited.
 Flexible: Updating of data can be done at a single point without making amendments at
multiple files. Databases can easily be extended to incorporate more records, thus
providing greater scalability. Also, facilitates easy application of SQL queries.
 Users: RDBMS supports client-side architecture storing multiple users together.
 Facilitates storage and retrieval of large amount of data.
 Easy Data Handling:
o Data fetching is faster because of relational architecture.
o Data redundancy or duplicity is avoided due to keys, indexes, and
normalization principles.
o Data consistency is ensured because RDBMS is based on ACID
properties for data transactions(Atomicity Consistency Isolation Durability).
 Fault Tolerance: Replication of databases provides simultaneous access and helps the
system recover in case of disasters, such as power failures or sudden shutdowns.
Disadvantages of RDBMS
 High Cost and Extensive Hardware and Software Support: Huge costs and setups
are required to make these systems functional.
 Scalability: In case of addition of more data, servers along with additional power, and
memory are required.
 Complexity: Voluminous data creates complexity in understanding of relations and
may lower down the performance.
 Structured Limits: The fields or columns of a relational database system is enclosed
within various limits, which may lead to loss of data.
Difference Between DBMS and RDBMS

DBMS RDBMS

DBMS stores data as file. RDBMS stores data in tabular form.

Data elements need to access Multiple data elements can be accessed at the
DBMS RDBMS

individually. same time

Data is stored in the form of tables which are


No relationship between data.
related to each other.

Normalization is not present. Normalization is present.

DBMS does not support distributed


RDBMS supports distributed database.
database.

It deals with small quantity of data. It deals with large amount of data.

Not all Codd rules are satisfied. All 12 Codd rules are satisfied.

Security is less More security measures provided.

Data fetching is slower for the large Data fetching is fast because of relational
amount of data. approach.

Conclusion
Relational databases store data in tables. Tables can grow large and have a multitude of
columns and records. Relational database management systems (RDBMSs) use SQL (and
variants of SQL) to manage the data in these large tables. The RDBMS you use is your
choice and depends on the complexity of your application.

3.2 Introduction to Call Level Interface (CLI) in JDBC


The Call Level Interface (CLI) in JDBC refers to a set of functions or methods that allow a
Java application to interact with a database through SQL queries and stored procedures. It
provides a way to execute database operations such as calling stored procedures, executing
SQL commands, and interacting with complex database operations.
CLI in JDBC can be used to execute SQL statements, retrieve result sets, handle database
connections, and manage database transactions. It typically involves using
CallableStatement to interact with stored procedures or functions within the database.
Key Concepts in Call Level Interface (CLI)
1. CallableStatement:
o The CallableStatement interface is a part of JDBC that is specifically used to
execute SQL stored procedures.
o It extends the PreparedStatement interface and allows the execution of stored
procedures with input and output parameters.
2. Stored Procedures:
o A stored procedure is a precompiled SQL statement or a set of SQL statements
that are stored in the database. It can accept input parameters, return output,
and be executed by a database server.
o Stored procedures help in encapsulating business logic, improving
performance, and reducing redundancy.
3. CallableStatement Methods:
o prepareCall(): This method is used to create a CallableStatement object for
executing a stored procedure.
o setXXX() methods: These are used to set the input parameters for the stored
procedure. For example, setInt(), setString(), etc.
o registerOutParameter(): This method is used to register the output
parameters that a stored procedure might return.
o execute(): This method is used to execute the stored procedure.

Steps to Use Call Level Interface in JDBC:


1. Establish a Connection:
o First, you need to establish a connection to the database using
DriverManager.getConnection().
2. Create a CallableStatement:
o Use the Connection.prepareCall() method to create a CallableStatement object
that will call the stored procedure.
3. Set Input Parameters:
o Use the setXXX() methods to set values for the input parameters for the stored
procedure.
4. Register Output Parameters:
o Use the registerOutParameter() method to register any output parameters for
the stored procedure.
5. Execute the CallableStatement:
o Call the execute() method to execute the stored procedure.
6. Retrieve Output:
o If the stored procedure has output parameters, use the getXXX() methods to
retrieve the result.
7. Close the Resources:
o Always close the CallableStatement and Connection objects to release
database resources.

Example Code for CallableStatement:

Here’s a simple example demonstrating the use of a Call Level Interface (CLI) in JDBC to
execute a stored procedure.
SQL Stored Procedure Example:
Sql Copy
CREATE PROCEDURE getEmployeeById(IN empId INT, OUT empName
VARCHAR(100))
BEGIN
SELECT name INTO empName
FROM employees
WHERE id = empId;
END;
Java Code Using JDBC CLI:
Java Copy
import java.sql.*;
public class JdbcCallableStatementExample {
public static void main(String[] args) {
Connection connection = null;
CallableStatement callableStatement = null;
try {
// Establish the connection to the database
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "password");

// Prepare the callable statement for the stored procedure


callableStatement = connection.prepareCall("{call getEmployeeById(?, ?)}");
// Set the input parameter (empId)
callableStatement.setInt(1, 101);// Register the output parameter (empName)
callableStatement.registerOutParameter(2, Types.VARCHAR);
// Execute the stored procedure
callableStatement.execute(); // Get the output parameter value
String employeeName = callableStatement.getString(2);
System.out.println("Employee Name: " + employeeName);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (callableStatement != null) callableStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}

Explanation of the Code:


1. Connection: A connection is established with the MySQL database using
DriverManager.getConnection().
2. CallableStatement: A CallableStatement object is created using the SQL CALL
statement that executes the stored procedure.
3. Input Parameter: The setInt() method is used to set the input parameter (empId).
4. Output Parameter: The registerOutParameter() method is used to register the output
parameter (empName).
5. Execution: The execute() method is used to run the stored procedure.

6. Retrieve Output: The result of the output parameter (empName) is retrieved using

the getString() method.


Benefits of Using CLI in JDBC:
 Code Reusability: Stored procedures encapsulate business logic, so you don't need to
repeat SQL code in multiple places.
 Performance: Stored procedures are precompiled, which can lead to faster execution,
especially for complex queries.
 Security: Using stored procedures reduces the risk of SQL injection attacks because
the SQL code is separated from user input.
Conclusion:
The Call Level Interface (CLI) in JDBC is a powerful feature that allows Java applications
to execute stored procedures in databases. It is highly beneficial for working with complex
business logic, reusable code, and improving performance. By using the CallableStatement
interface, Java developers can interact with stored procedures and functions in an efficient
and secure manner.

3.3 Introduction to JDBC:


JDBC Overview
• JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database.
• JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
• JDBC stands for Java Database Connectivity, which 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 mentioned below that are 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.

Applications of JDBC :
• Fundamentally, 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, such as:
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
• All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
• JDBC provides the same capabilities as ODBC, allowing Java programs to contain database
independent code.

The JDBC 4.0 Packages :


• The java.sql and javax.sql are the primary packages for JDBC 4.0.
• It offers the main classes for interacting with your data sources.
• The new features in these packages include changes in the following are as:
 Automatic database driver loading.
 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
Connection and statement interface enhancements.
▪ National character set support.
▪ SQL ROWID access.
▪ SQL 2003 XML data type support.

3.4 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.
• Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application

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
using communication sub protocol. 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.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.
 Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
 Statement: You 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.

3.5 JDBC Driver :


• JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
• For example, using JDBC drivers enable you to open database connections and to interact
with it by sending SQL or database commands then receiving results with Java.
• The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implement the java.sql.Driver interface in their database driver. JDBC Drivers Types
• JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates.
• Sun has divided the implementation types into four categories:
 Type 1: JDBC-ODBC Bridge Driver
 Type 2: JDBC-Native API
 Type 3: JDBC-Net pure Java
 Type 4: 100% Pure Java

Type 1: JDBC-ODBC Bridge Driver


• In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine.
• Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
• The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API :


• In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database.
• These drivers are typically provided by the database vendors and used in the same manner
as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client
machine.
• If we change the Database, we have to change the native API, as it is specific to a database
and they are mostly obsolete now, but you may realize some speed increase with a Type 2
driver, because it eliminates ODBC's overhead.
 The Oracle Call Interface (OCI) driver is an example of a Type 2 driver

Type 3: JDBC-Net pure Java :


• In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server.

The socket information is then translated by the middleware application server into the call
format required by the DBMS, and forwarded to the database server.
• This kind of driver is extremely flexible, since it requires no code installed on the client and
a single driver can actually provide access to multiple databases.
• You can think of the application server as a JDBC "proxy," meaning that it makes calls for
the client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
• Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.

Type 4: 100% Pure Java :


• In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
database through socket connection. This is the highest performance driver available for the
database and is usually provided by the vendor itself.
• This kind of driver is extremely flexible, you don't need to install special software on the
client or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

3.6 Establishing a JDBC Connection:


JDBC Connection Class
The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps:
3.6.1 Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
3.6.2 Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
3.6.3 Database URL Formulation: This is to create a properly formatted address that points
to the database to which you wish to connect.
3.6.4 Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.

3.6.1 Import JDBC Packages :


• The Import statements tell the Java compiler where to find the classes you reference in your
code and are placed at the very beginning of your source code.
• To use the standard JDBC package, which allows you to select, insert, update, and delete
data in SQL tables, add the following imports to your source code
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support

3.6.2 Register JDBC Driver :


• You must register the driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into the memory, so it can be utilized
as an implementation of the JDBC interfaces.
• You need to do this registration only once in your program. You can register a driver in one
of two ways.
1. Approach I - Class.forName()
• The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver registration configurable and
portable.
• The following example uses Class.forName( ) to register the Oracle driver:-

try {
Class.forName("oracle.jdbc.driver.OracleDriver"); }
catch(ClassNotFoundException ex)
{ System.out.println("Error: unable to load driver class!");
System.exit(1); }
 You can use getInstance() method to work around noncompliant JVMs, but then
you'll have to code for two extra Exceptions as follows –

try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}

2. Approach II - DriverManager.registerDriver()
• The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
• You should use the registerDriver() method if you are using a non-JDK compliant JVM,
such as the one provided by Microsoft.
• The following example uses registerDriver() to register the Oracle driver
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver ); }
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");

System.exit(1);
}

3.6.3 Database URL Formulation :


• After loaded the driver, you can establish a connection using the
DriverManager.getConnection() method.
• The following are list the three overloaded DriverManager.getConnection() methods:
 getConnection(String url)
 getConnection(String url, Properties prop)
 getConnection(String url, String user, String password)
• Here each form requires a database URL. A database URL is an address that points to your
database.
• Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
• Following table lists down the popular JDBC driver names and database URL.
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/
database Name
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:
port
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Drive jdbc:db2:hostname:port
r Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname:
port
Number/databaseName

 All the highlighted part in URL format is static and you need to change only the
remaining part as per your database setup.

3.6.4 Create Connection Object


• There are three forms of DriverManager.getConnection() method to create a connection
object.
1. Using a Database URL with a username and password
• The most commonly used form of getConnection() requires you to pass a database URL, a
username, and a password:
• Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value
for the database portion of the URL.
• If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your
Oracle listener is configured to listen on port 1521, and your database name is EMP, then
complete database URL would be:

jdbc:oracle:thin:@amrood:1521:EMP

Now call getConnection() method with appropriate username and password to get
a Connection object as follows:

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";


String USER = "username";
String PASS = "password"
2. Using Only a Database URL
• A second form of the DriverManager.getConnection( ) method requires only a
database

DriverManager.getConnection(String url);

However, in this case, the database URL includes the username and password and has
the
jdbc:oracle:driver:username/password@database

So, the above connection can be created as follows:


String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);

4. Using a Database URL and a Properties Object

A third form of the DriverManager.getConnection( ) method requires a database URL


and a
Properties object –
DriverManager.getConnection(String url, Properties info);

A Properties object holds a set of keyword-value pairs. It is used to pass driver


properties
to the driver during a call to the getConnection() method.
• To make the same connection made by the previous examples, use the following
code –
import java.util.*;
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Connection conn = DriverManager.getConnection(URL, info);

Closing JDBC Connections


• At the end of your JDBC program, it is required explicitly to close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will
close the connection when it cleans up stale objects.
• Relying on the garbage collection, especially in database programming, is a very poor
programming practice. You should make a habit of always closing the connection with the
close() method associated with connection object.
• To ensure that a connection is closed, you could provide a 'finally' block in your code. A
finally block always executes, regardless of an exception occurs or not.
• To close the above opened connection, you should call close() method as follows:

conn.close();

• Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.

3.7 USING STATEMENT:


JDBC Statements

• Once a connection is obtained we can interact with the database.


• The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the
methods and properties that enable you to send SQL or PL/SQL commands and receive data
from your database.
• They also define methods that help bridge data type differences between Java and SQL data
types used in a database.
• The following table provides a summary of each interface's purpose to decide on the
interface to use.

3.7.1 Statement Objects


Creating Statement Object:
Before you can use a Statement object to execute a SQL statement, you need to create
one using the Connection object's createStatement( ) method, as in the following
example:
Once you've created a Statement object, you can then use it to execute an SQL statement with
one of its three execute methods.
• boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be
retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or
when you need to use truly dynamic SQL.
• int executeUpdate (String SQL): Returns the number of rows affected by the execution of
the SQL statement. Use this method to execute SQL statements for which you expect to get a
number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
• ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when
you expect to get a result set, as you would with a SELECT statement.

Closing Statement Object


Just as you close a Connection object to save database resources, for the same reason you
should also close the Statement object. A simple call to the close() method will do the job. If
you close the Connection object first, it will close the Statement object as well. However, you
should always explicitly close the Statement object to ensure proper cleanup.

3.7.2 The PreparedStatement Objects

The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object. This statement
gives you the flexibility of supplying arguments dynamically.

Creating PreparedStatement Object

All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.

• The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive an SQLException.
• Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which starts at 0.

All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the parameters.

Closing PreparedStatement Object


• Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
• A simple call to the close() method will do the job. If you close the Connection object first,
it
will close the PreparedStatement object as well. However, you should always explicitly
close the PreparedStatement object to ensure proper cleanup.

3.7.3 The CallableStatement Objects

• Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database
stored procedure.
Creating CallableStatement Object
Suppose, you need to execute the following Oracle stored procedure:

Note: Above stored procedure has been written for Oracle, but we are working with MySQL
database so, let us write same stored procedure for MySQL as follows to create it in EMP
database
 Three types of parameters exist: IN, OUT, and INOUT.
 The PreparedStatement object only uses the IN parameter.
 The CallableStatement object can use all the three. The following are the definitions:

The following code snippet shows how to employ the Connection.prepareCall() method
to instantiate a CallableStatement object based on the preceding stored procedure –

The String variable SQL, represents the stored procedure, with parameter placeholders.
• Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement, or you will receive an
SQLException.
• If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type
you are binding.
• When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method binds
the JDBC data type, to the data type that the stored procedure is expected to return.
• Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.

Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
• A simple call to the close() method will do the job. If you close the Connection object first,
it will close the CallableStatement object as well. However, you should always explicitly
close the CallableStatement object to ensure proper cleanup.

3.8 Scrollable and Updatable Result Set:


A scrollable and updatable result set typically refers to a type of result set (often used in
database programming) that allows you to:

1. Scroll: Navigate through the rows of the result set, both forward and backward.
2. Update: Modify the data in the result set directly, allowing changes to be made
without having to re-query the database or recreate the result set.

Use in Databases

Scrollable and updatable result sets are commonly found in database systems and are used in
environments such as JDBC (Java Database Connectivity) or ODBC (Open Database
Connectivity), where a developer wants to interact with query results dynamically.

Key Features:
1. Scrollability: The result set is not static; you can move backward and forward
through the rows. This can be helpful in cases where you need to implement a UI
feature (like pagination) or simply need to process the result set in chunks.
o In JDBC, the result set is scrollable when you set the appropriate ResultSet
type (e.g., ResultSet.TYPE_SCROLL_INSENSITIVE or
ResultSet.TYPE_SCROLL_SENSITIVE).
oScroll operations include: first(), last(), next(), previous(), absolute(), and
relative().
2. Updating ResultSets: The ResultSet interface contains a collection of update
methods for updating the data of a result set.

• As with the get methods, there are two update methods for each data type −
▪ One that takes in a column name.
▪ One that takes in a column index.
• For example, to update a String column of the current row of a result set, you would
use one of the following updateString() methods:

There are update methods for the eight primitive data types, as well as String, Object,
URL, and the SQL data types in the java.sql package.
• Updating a row in the result set changes the columns of the current row in the
ResultSet object, but not in the underlying database. To update your changes to the row
in the database, you need to invoke one of the following methods.

The result set allows you to modify the underlying data (insert, update, delete rows) directly
in the result set. When changes are made to the result set, these changes can be committed
back to the database.
In JDBC, you can achieve updatability by specifying a ResultSet with the type
ResultSet.CONCUR_UPDATABLE. This allows you to use methods like updateString(),
updateInt(), etc., on the current row.

Practical Example:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "user",
"password");
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
// Scroll through the result set
rs.first();
System.out.println(rs.getString("name")); // Print first employee's name
// Update a row
rs.updateString("name", "John Doe");
rs.updateRow();
// Scroll to next row
rs.next();
System.out.println(rs.getString("name")); // Print updated name for the next employee
// Commit changes to the database
conn.commit();

3.9 Managing Transactions in JDBC :


In JDBC (Java Database Connectivity), managing transactions is a critical part of ensuring
that your database operations are executed correctly, consistently, and safely. A transaction
allows you to execute multiple SQL operations as a single unit of work, ensuring either all
operations are successful (commit) or none at all (rollback) in case of an error.

Here’s how to manage transactions in JDBC:

3.9.1. Disable Auto-Commit Mode


By default, JDBC operates in auto-commit mode, meaning every SQL statement is treated
as a transaction, and each statement is automatically committed after execution. To manage
transactions manually, you need to disable this behavior.

Connection connection = DriverManager.getConnection("jdbc:your_database_url",


"username", "password");
connection.setAutoCommit(false); // Disable auto-commit mode

3.9.2. Perform Database Operations


Once auto-commit is turned off, you can execute multiple SQL operations (like INSERT,
UPDATE, or DELETE) as part of a transaction.

Statement stmt = connection.createStatement();


try {
stmt.executeUpdate("INSERT INTO employees (name, position) VALUES ('Alice',
'Manager')");
stmt.executeUpdate("UPDATE employees SET position = 'Senior Manager' WHERE
name = 'Bob'");
// Add more operations as needed
} catch (SQLException e) {
connection.rollback(); // Rollback in case of error
e.printStackTrace();
}
3.9.3. Commit the Transaction
If all database operations execute successfully, commit the transaction to make the changes
permanent.

connection.commit(); // Commit the transaction

3.9.4. Rollback in Case of Errors


If there is an exception (like a SQLException) during any of the operations, you should
rollback the transaction to revert all changes made so far.

connection.rollback(); // Rollback the transaction in case of error

3.9.5. Handling Exceptions and Closing Resources


You should use a try-catch-finally block to ensure proper exception handling and
resource management.

Connection connection = null;


Statement stmt = null;
try {
connection = DriverManager.getConnection("jdbc:your_database_url", "username",
"password");
connection.setAutoCommit(false); // Disable auto-commit

stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO employees (name, position) VALUES ('Alice',
'Manager')");
stmt.executeUpdate("UPDATE employees SET position = 'Senior Manager' WHERE
name = 'Bob'");

connection.commit(); // Commit if no errors


} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback(); // Rollback in case of error
} catch (SQLException ex) {
ex.printStackTrace(); // Handle rollback error
}
}
e.printStackTrace(); // Log original error
} finally {
// Close resources in the finally block
try {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace(); // Handle resource close error
}
}

3.9.6. Savepoints (Optional)


If you need finer control over your transactions, you can set savepoints within a transaction.
A savepoint allows you to rollback to a specific point in the transaction without rolling back
the entire transaction.

Savepoint savepoint = connection.setSavepoint("Savepoint1");

try {
stmt.executeUpdate("INSERT INTO employees (name, position) VALUES ('Alice',
'Manager')");
stmt.executeUpdate("UPDATE employees SET position = 'Senior Manager' WHERE
name = 'Bob'");

// Rollback to the savepoint if necessary


connection.rollback(savepoint);
connection.commit(); // Commit remaining operations
} catch (SQLException e) {
e.printStackTrace();
connection.rollback(savepoint); // Rollback to savepoint in case of error
}

3.10 Extensible Markup Language(XML):

3.10.1 Introduction to XML

XML (Extensible Markup Language) is a versatile, flexible, and widely used language for
representing structured data in a readable and self-descriptive format. It was developed by the
World Wide Web Consortium (W3C) in 1998, primarily to meet the need for data
exchange between diverse systems and applications over the internet.
Unlike HTML (HyperText Markup Language), which is focused on presentation, XML is
focused on data and is designed to be both human-readable and machine-readable.
Key Features of XML
1. Self-Descriptive:
o XML documents are made up of tags (elements) that describe the data they
contain.
o It’s easy to understand since the data is labeled in a clear structure, making it
possible for both machines and humans to comprehend.
2. Extensible:
o Unlike HTML, where predefined tags are used, XML allows you to define
your own tags. This makes it extremely flexible for various applications.
3. Hierarchical Structure:
o XML is based on a tree-like structure, where elements are nested inside each
other. The top element is often referred to as the root, and the nested elements
are called child elements.
4. Platform-Independent:
o XML is plain text and not bound to any specific programming language or
operating system. It can be processed by any device or platform that supports
XML standards.
5. Human-Readable and Machine-Readable:
o XML files are written in plain text, making them easy for humans to read and
modify. At the same time, they are structured in a way that software
applications can process automatically.
Basic XML Structure
A basic XML document consists of the following key components:
1. Prolog: This is an optional section at the beginning of the XML file that can specify
the version and encoding of the XML document.
<?xml version="1.0" encoding="UTF-8"?>
2. Elements (Tags): XML data is wrapped in tags, with the data enclosed inside the
opening <tag> and closing </tag> tags. Tags are case-sensitive.
<employee>
<name>John Doe</name>
<age>30</age>
<department>HR</department>
</employee>
 <employee> is the root element.
 <name>, <age>, and <department> are child elements of <employee>.
3. Attributes: Elements can have attributes that provide additional information about an
element. Attributes are placed inside the opening tag.

<employee id="101">
<name>John Doe</name>
<age>30</age>
<department>HR</department>
</employee>
4. Comments: You can add comments to XML files using <!-- -->.
<!-- This is a comment -->
<employee>
<name>John Doe</name>
</employee>
Example XML Document
Here's a simple example of an XML document:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee id="101">
<name>John Doe</name>
<age>30</age>
<department>HR</department>
</employee>
<employee id="102">
<name>Jane Smith</name>
<age>25</age>
<department>Engineering</department>
</employee>
</company>

 The root element is <company>.


 Inside the <company>, there are two <employee> elements, each with an id attribute
and several child elements (<name>, <age>, <department>).
Why XML is Important
1. Data Interchange:
o XML is commonly used for exchanging data between systems that may not
use the same programming languages or platforms.
o It is used in web services (e.g., SOAP) and APIs to send and receive data over
the internet.
2. Configuration Files:
o XML is often used for configuration files in applications where settings need
to be stored in a structured format (e.g., pom.xml in Maven or web.xml in Java
web applications).
3. Document Storage:
o Many document formats, like SVG (for vector graphics) and XHTML (for
web pages), use XML as their base format.
4. Standards:
o Many standards, such as RSS (Really Simple Syndication) and Atom for
feeds, use XML.
o XSLT (Extensible Stylesheet Language Transformations) and XPath (XML
Path Language) are widely used for transforming and querying XML data.

Advantages of XML

 Portability: As XML is text-based, it's platform-independent and can be transferred


easily between different systems.
 Extensibility: You can create your own tags to suit the needs of your application.
 Data Integrity: XML enforces a strict structure and data format, reducing errors.
 Interoperability: XML can be used with various technologies and programming
languages for data sharing.
Disadvantages of XML

 Verbosity: XML files can be large and repetitive due to the opening and closing tags.
 Performance: Parsing and processing large XML files can be slower compared to
binary formats.
 Complexity: Creating and maintaining complex XML schemas or documents can
become difficult as the document size increases.

XML vs. Other Formats

 XML vs JSON:
XML is more verbose than JSON (JavaScript Object Notation), which is often
o
preferred for web APIs due to its compactness and ease of use.
o JSON is also easier to parse and manipulate in many programming languages
compared to XML.
 XML vs CSV:
o CSV (Comma-Separated Values) is much simpler and smaller in size but lacks
the structure and hierarchical features of XML. XML is better suited for
representing complex relationships and nested data.

3.10.2 DOM Using JAXP (Java API for XML Processing) -


The Document Object Model (DOM) is a programming interface for XML documents. It
represents the document as a tree structure, where each element in the document is a node in
the tree. Using JAXP (Java API for XML Processing), you can parse, manipulate, and
query XML documents using the DOM model.

Key Concepts of DOM:


1. Document: The root node representing the entire XML document.
2. Element: A node representing an XML element.
3. Node: A generic class representing any type of XML node (e.g., element, text,
attribute).
4. NodeList: A collection of nodes, typically returned by methods that find nodes by tag
name or other criteria.
5. Attributes: Elements may have attributes, which are also represented as nodes.

JAXP DOM Parsing Process:

1. DocumentBuilderFactory: This class provides a way to create a DocumentBuilder,


which is responsible for parsing XML into a Document object (in DOM form).
2. DocumentBuilder: This class is used to parse an XML file and convert it into a
Document object, which is a tree representation of the XML document.
3. Document: The Document object is the top-level object that represents the XML
document as a whole, and it allows access to the elements and attributes.
4. Element: Each element in the XML document is represented by an Element object,
which is a subclass of Node.

Steps to Parse XML Using DOM in JAXP:

1. Create a DocumentBuilderFactory instance:


o This is the factory class used to create the DocumentBuilder.
o DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
2. Create a DocumentBuilder instance:
o The DocumentBuilder is used to parse the XML document into a DOM
Document object.
o DocumentBuilder builder = factory.newDocumentBuilder();
3. Parse the XML file:
o Use the parse() method to read the XML file and generate a Document
object.
o Document document = builder.parse(inputFile);
4. Normalize the document:
o Normalization cleans up the document by eliminating any redundant or
malformed whitespace.
o document.getDocumentElement().normalize();
5. Traverse the Document:
o You can traverse the XML document using the getElementsByTagName() or
getChildNodes() methods to get NodeList objects, and then process each
node individually.
o You can access node attributes, element names, text content, etc.

Advantages of DOM Parsing:

1. Complete Document in Memory: The entire XML document is loaded into memory,
so you can easily navigate, query, and modify the document.
2. Ease of Navigation: You can easily move around the document using various
methods to access different parts (e.g., elements, attributes).
3. Modification: DOM allows you to make changes to the XML document by
modifying nodes, adding new elements, and removing nodes.

Disadvantages of DOM Parsing:

1. Memory Intensive: Since the entire XML document is loaded into memory, it can be
inefficient for large XML files.
2. Slower for Large Documents: Due to the need to load and manipulate the entire
document, it can be slower for processing large XML files compared to other parsing
methods like SAX (Simple API for XML).
Common Methods and Interfaces:

1. DocumentBuilderFactory:
o newInstance(): Creates a new instance of the DocumentBuilderFactory.
o setValidating(): Enables or disables validation.
o setNamespaceAware(): Sets whether the factory is namespace-aware.
2. DocumentBuilder:
o parse(): Parses an XML file and returns a Document object.
o newDocument(): Creates a new, empty Document object.
3. Document:
o getDocumentElement(): Returns the root element of the document.
o createElement(): Creates a new element.
o getElementsByTagName(): Returns a NodeList of elements with the specified
tag name.
4. Element:
o getAttribute(): Gets the value of the attribute with the specified name.
o getElementsByTagName(): Gets child elements by tag name.
o getTextContent(): Gets the text content of an element or its children.
5. Node:
o getNodeType(): Returns the type of the node (element, text, attribute, etc.).
o getNodeName(): Returns the name of the node (e.g., "student" for an element
node).
o getChildNodes(): Returns a NodeList of child nodes.

Example: Parsing an XML File Using DOM


import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

public class DOMParserExample {


public static void main(String[] args) {
try {
// Create DocumentBuilderFactory and DocumentBuilder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

// Parse the XML file into a DOM Document


File inputFile = new File("students.xml");
Document document = builder.parse(inputFile);

// Normalize the document (optional)


document.getDocumentElement().normalize();

// Print root element


System.out.println("Root element: " +
document.getDocumentElement().getNodeName());

// Get all student elements


NodeList nodeList = document.getElementsByTagName("student");

// Traverse the NodeList


for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
// Print student information
System.out.println("Student ID: " + element.getAttribute("id"));
System.out.println("Name: "+
element.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Age: "+
element.getElementsByTagName("age").item(0).getTextContent());
System.out.println("----------");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Sample XML (students.xml):

<?xml version="1.0" encoding="UTF-8"?>


<school>
<student id="1">
<name>John Doe</name>
<age>15</age>
</student>
<student id="2">
<name>Jane Smith</name>
<age>16</age>
</student>
</school>

 DOM is suitable when you need to manipulate or query an entire XML document in
memory.
 It is good for small to medium-sized XML files.
 JAXP provides the necessary tools to parse, traverse, and manipulate XML using the
DOM model, offering flexibility and ease of use in Java.

You might also like