Advanced Java Unit-I
Advanced Java Unit-I
UNIT–I
Introduction:
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 provides a set of APIs to perform various common database operations, such
as:
At its core, JDBC is a specification that defines a comprehensive set of interfaces enabling
platform-independent access to various databases. Java supports the creation of multiple types of
executables, including:
Java Applications
Java Applets
Java Servlets
JavaServer Pages (JSPs)
Enterprise JavaBeans (EJBs)
Each of these Java-based components can utilize a JDBC driver to connect to a database and
interact with the stored data effectively.
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 and JDBC Driver API.
JDBC Programming
Page 1
Figure 1.1 JDBC Architecture
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.
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.
JDBC Programming
Page 2
Types of JDBC Drivers
A JDBC Driver is a middleware driver that translates the JDBC calls to the vendor –
specific APIs.
To access the data there is a need of database driver, probably supplied by the database
vendor or by a J2EE service provider. A driver is nothing but an implementation of
various interfaces specified in java.sql and javax.sql packages.
JDBC drivers are client-side adapters that translate requests from Java programs into a
protocol understood by the DBMS.
JDBC drivers are software components that implement the interfaces in the JDBC API,
allowing Java applications to interact with a database
There are four different approaches to connect an application to a database server via database
driver.
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Pure Java driver
• Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the
database.
JDBC Programming
Page 3
• The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls.
• Type-1 driver is also called Universal driver because it can be used to connect to any of
the databases.
Advantages
• This driver software is built-in with JDK so no need to install separately.
• It is a database independent driver.
Disadvantages
• A common driver is used to connect with different databases, but this makes the data
transfer less secure. Also, the ODBC bridge driver needs to be installed on every client
computer separately.
• Since the Type-1 driver is not written in Java, it cannot run on all platforms, so it's not
portable
2. Native-API Driver - Type 2 Driver
•
The Native API driver uses the client -side libraries of the database.
• This driver converts JDBC method calls into native calls of the database API.
• In order to interact with different database, this driver needs their local API, so data
transfer is much more secure as compared to type-1 driver.
• This driver is not fully written in Java that is why it is also called Partially Java driver.
Advantage
• Native-API driver gives better performance than JDBC-ODBC bridge driver.
• More secure compared to the type-1 driver.
Disadvantages
• Driver needs to be installed separately in individual client machines
• The Vendor client library needs to be installed on client machine.
• Type-2 driver isn't written in java, that's why it isn't a portable driver
• It is a database dependent driver.
Network Protocol Driver - Type 3 Driver
JDBC Programming
Page 4
•
The Network Protocol driver uses middleware that converts JDBC calls directly or
indirectly into the vendor-specific database protocol.
• No need of individual client-side installation because here all the database connectivity
drivers are present in a single server.
Advantages
• Type-3 drivers are fully written in Java, hence they are portable drivers.
• No client side library is required because of application server that can perform many
tasks.
• Switch facility to switch over from one database to another database.
Disadvantages
• Network support is required on client machine.
• Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
Pure Java Driver - Type 4 Driver
JDBC Programming
Page 5
•
Type-4 driver is also called native protocol driver.
• This driver interact directly with database.
• It does not require any native database library, that is why it is also known as Thin
Driver
Advantages
• Does not require any native library and Middleware server, so no client-side or server-
side installation.
• It is fully written in Java language, hence they are portable drivers.
Disadvantage
• If the database changes, a new driver may be needed
OUTPUT
Connected to database.
Record inserted.
ID Name Marks
1 sai 85
Types of Statements
• Statement interface is used to create and execute SQL queries in Java applications.
• JDBC provides three types of statements to interact with the database:
1. Statement
2. Prepared Statement
3. Callable Statement
JDBC Programming
Page 8
Statement
Statement object is used for general-purpose access to databases and is useful for executing
static SQL statements at runtime.
Syntax:
• Statement statement = connection.createStatement();
• Once the Statement object is created, there are three ways to execute it.
i. execute(String SQL): It is used to executes any SQL statements (like SELECT,
INSERT, UPDATE or DELETE). If the ResultSet object is retrieved, then it returns true
else false is returned.
ii. executeUpdate(String SQL): It is used to executes SQL statements (like INSERT,
UPDATE or DELETE). It returns the number of rows affected by the SQL statement.
iii. ResultSet executeQuery(String SQL): It is used to executes the SELECT query. It
returns a ResultSet object that contains the data retrieved by the query.
// Java Program illustrating Create Statement in JDBC
import java.sql.*;
public class statex {
public static void main(String[] args) {
try {
JDBC Programming
Page 9
Prepared Statement
• A Prepared Statement represents a precompiled SQL statement that can be executed
multiple times.
• It accepts parameterized SQL queries, with ? as placeholders for parameters, which can
be set dynamically.
Methods of PreparedStatement
Method Description
Syntax
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);
// Set parameters
pstmt.setString(1, "John");
pstmt.setInt(2, 25);
// Execute the query
pstmt.executeUpdate();
JDBC Programming
Page 10
Example program for INSERT using PreparedStatement
import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
// JDBC URL, username and password of MySQL server
String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root";
String password = "your_password_here";
// SQL Insert Query
String query = "INSERT INTO students (id, name, age) VALUES (?, ?, ?)";
try {
// Step 1: Load JDBC Driver (optional for newer versions)
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish Connection
Connection con = DriverManager.getConnection(url, user, password);
// Step 3: Create PreparedStatement
PreparedStatement pstmt = con.prepareStatement(query);
// Step 4: Set values to the placeholders (?)
pstmt.setInt(1, 101); // Set id
pstmt.setString(2, "John Doe"); // Set name
pstmt.setInt(3, 20); // Set age
// Step 5: Execute the query
int rowsInserted = pstmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted successfully!");
// Step 6: Close resources
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Methods of CallableStatement
Method Purpose
setInt(paramIndex, value) Sets input parameter
registerOutParameter(index, type) Registers an output parameter
getInt(index) or getString(index) Retrieves output value
JDBC Programming
Page 12
execute() Executes the stored procedure
Methods to Execute
• execute(): Executes the stored procedure and returns a boolean indicating whether the
result is a ResultSet (true) or an update count (false).
• executeQuery(): Executes a stored procedure that returns a ResultSet.
• executeUpdate(): Executes a stored procedure that performs an update and returns the
number of rows affected
JDBC Programming
Page 13
}
}
}
Advantages of callable statements
• Reuse of logic stored in the database.
• Reduces network traffic (less SQL code sent).
• Improves performance with precompiled logic.
• Better security through stored procedures.
Exploring ResultSet Operations
• The ResultSet is essentially a table of data where each row represents a record and each
column represents a field in the database.
• The ResultSet has a cursor that points to the current row in the ResultSet and we can able
to navigate in ResultSet by using the next(), previous(), first(), and last() methods.
• We can retrieve data by using different methods like getString(), getInt(),
getDouble() and other methods.
• In Java, the ResultSet is the Object which is used for holding the result of a database
query typically the SQL select statement
• Syntax
• try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table");
while (rs.next()) {
// Process the result set
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace(); // Handle the exception
}
Navigating a ResultSet
• In JDBC, when we execute a query like SELECT * FROM students, the result is stored in
a ResultSet object.
• The ResultSet object has a cursor that starts before the first row, and we can move it
using:
JDBC Programming
Page 14
Example Program: Navigating ResultSet
import java.sql.*;
public class ResultSetNavigationExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // your DB name
String user = "root";
String password = "password"; // replace with your MySQL password
try
{
Connection conn = DriverManager.getConnection(url, user, password);
// Create scrollable ResultSet
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
){
System.out.println("Using next():");
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}
System.out.println("\nUsing last():");
rs.last(); // Move to last row
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
System.out.println("\nUsing first():");
rs.first(); // Move to first row
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
System.out.println("\nUsing previous():");
if (rs.previous()) { // Move before first, so check
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
} else {
System.out.println("No previous row (cursor was at first row)");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC Programming
Page 15
Batch Updates in JDBC
Grouping a set of INSERT or, UPDATE or, DELETE commands and execute them at
once this mechanism is known as a batch update.
Advantages of BatchUpdate
• Reduces network overhead.
• Improves execution speed for bulk operations.
• Especially useful in loops when inserting/updating many records.
Example Program
import java.sql.*;
public class BatchInsertExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root";
String password = "your_password_here";
try {
// Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to DB
Connection con = DriverManager.getConnection(url, user, password);
// Disable auto-commit for batch
con.setAutoCommit(false);
// Create Statement
Statement stmt = con.createStatement();
JDBC Programming
Page 16
// Add multiple insert statements to batch
stmt.addBatch("INSERT INTO students (id, name) VALUES (201, 'Alice')");
stmt.addBatch("INSERT INTO students (id, name) VALUES (202, 'Bob')");
stmt.addBatch("INSERT INTO students (id, name) VALUES (203, 'Charlie')");
// Execute batch
int[] result = stmt.executeBatch();
// Commit the batch
con.commit();
System.out.println("Batch executed successfully!");
// Close resources
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output: Batch executed successfully!
JDBC Programming
Page 17
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
createTable(conn);
while (true) {
System.out.println("\n1. Create");
System.out.println("2. Read");
System.out.println("3. Update");
System.out.println("4. Delete");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline
if (choice == 1) {
insertData(conn, scanner);
} else if (choice == 2) {
readData(conn);
} else if (choice == 3) {
updateData(conn, scanner);
} else if (choice == 4) {
deleteData(conn, scanner);
} else if (choice == 5) {
System.out.println("Exiting...");
break;
} else {
System.out.println("Invalid choice.");
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, email);
pstmt.executeUpdate();
pstmt.close();
System.out.println("User added.");
}
System.out.println("\nUsers:");
while (rs.next()) {
System.out.printf("ID: %d | Name: %s | Email: %s%n",
rs.getInt("id"),
rs.getString("name"),
rs.getString("email"));
}
rs.close();
stmt.close();
}
JdbcRowSet Example
import javax.sql.rowset.JdbcRowSet;
import com.sun.rowset.JdbcRowSetImpl;
while (jrs.next()) {
System.out.println("ID: " + jrs.getInt("id") + ", Name: " + jrs.getString("name"));
JDBC Programming
Page 21
}
jrs.close();
}
}
CachedRowSet
• Disconnected RowSet.
• Retrieves data from DB and stores it in memory; does not require a continuous
connection.
CachedRowSet Example
import javax.sql.rowset.CachedRowSet;
import com.sun.rowset.CachedRowSetImpl;
while (crs.next()) {
System.out.println("ID: " + crs.getInt("id") + ", Name: " + crs.getString("name"));
}
WebRowSet
• A subclass of CachedRowSet.
• Can read/write data in XML format.
• Useful for web-based applications and data transfer.
WebRowSet Example
import javax.sql.rowset.WebRowSet;
import com.sun.rowset.WebRowSetImpl;
import java.io.FileWriter;
wrs.close();
System.out.println("Data written to students.xml");
}
}
JoinRowSet
• Allows joining data from multiple RowSets.
• Helps perform SQL-like JOIN operations in Java code
JoinRowSet Example
import javax.sql.rowset.JoinRowSet;
import com.sun.rowset.JoinRowSetImpl;
import com.sun.rowset.CachedRowSetImpl;
while (jrs.next()) {
JDBC Programming
Page 23
System.out.println("Name: " + jrs.getString("name") + ", Marks: " +
jrs.getInt("marks"));
}
}
}
FilteredRowSet
• Subtype of CachedRowSet.
• Allows filtering rows using custom logic without writing SQL WHERE clause.
FilteredRowSet Example
import javax.sql.rowset.FilteredRowSet;
import com.sun.rowset.FilteredRowSetImpl;
import com.sun.rowset.RowSetFilterImpl;
while (frs.next()) {
System.out.println("ID: " + frs.getInt("id") + ", Name: " + frs.getString("name"));
}
}
}
import javax.sql.rowset.Predicate;
JDBC Programming
Page 25
• Transactions enable us to control if, and when, changes are applied to the database. It
treats a single SQL statement or a group of SQL statements as one logical unit, and if any
statement fails, the whole transaction fails.
• To enable manual- transaction support instead of the auto-commit mode that the JDBC
driver uses by default, use the Connection object's setAutoCommit() method.
• If we pass a boolean false to setAutoCommit( ), we turn off auto-commit. we can pass a
boolean true to turn it back on again.
Syntax:
conn.setAutoCommit(false);
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
JDBC Programming
Page 26
// Inserting a new account
stmt.executeUpdate("INSERT INTO accounts VALUES (101, 'Alice', 1000)");
// Updating balance
stmt.executeUpdate("UPDATE accounts SET balance = balance - 500 WHERE id =
101");
} catch (Exception e) {
// Step 5: Rollback in case of error
if (conn != null) {
try {
conn.rollback();
System.out.println("Transaction rolled back due to error!");
} catch (SQLException se) {
System.out.println("Error during rollback: " + se.getMessage());
}
}
System.out.println("Error: " + e.getMessage());
} finally {
// Step 6: Clean up resources
if (conn != null) {
try {
conn.setAutoCommit(true); // Restore auto-commit
conn.close();
} catch (SQLException ignore) {
// Ignored
}
}
}
}
}
Using saveponits
• When we set a savepoint we define a logical rollback point within a transaction.
• If an error occurs past a savepoint, we can use the rollback method to undo either all the
changes or only the changes made after the savepoint.
The Connection object has two new methods that help to manage savepoints −
1. setSavepoint(String savepointName) − Defines a new savepoint. It also returns a
Savepoint object.
2. releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it
requires a Savepoint object as a parameter. This object is usually a savepoint generated
by the setSavepoint() method.
Example
JDBC Programming
Page 27
import java.sql.*;
try {
// Load and register JDBC driver (optional for newer versions)
Class.forName("com.mysql.cj.jdbc.Driver");
2. Which JDBC driver type requires native DB API to communicate with the database?
a) Type 1
b) Type 2
c) Type 3
d) Type 4
Answer: b) Type 2
3. Which of the following is a valid JDBC driver type for Java applications?
a) Type 1
b) Type 3
c) Both a and b
d) Type 5
a) ResultSet
b) Statement
c) Driver
d) Connection
Answer: b) Statement
5. Which JDBC class is used to represent the result set of an SQL query?
a) Statement
b) ResultSet
c) CallableStatement
d) Connection
Answer: b) ResultSet
6. Which of the following methods does not belong to the Statement interface?
a) executeQuery()
b) executeUpdate()
c) prepareStatement()
d) execute()
Answer: c) prepareStatement()
a) Statement
b) PreparedStatement
c) CallableStatement
d) DataStatement
Answer: d) DataStatement
JDBC Programming
Page 30
9. Which JDBC method is used to update the database using a batch of SQL commands?
a) addBatch()
b) executeBatch()
c) executeUpdate()
d) executeQuery()
Answer: b) executeBatch()
a) Forward
b) Backward
c) Both
d) None
Answer: a) Forward
a) executeQuery()
b) executeUpdate()
c) execute()
d) executeCallable()
Answer: c) execute()
JDBC Programming
Page 31
14. In a CRUD application, what does "C" stand for?
a) Create
b) Change
c) Copy
d) Classify
Answer: a) Create
a) Statement
b) Connection
c) DriverManager
d) ResultSet
Answer: b) Connection
a) CallableStatement
b) Statement
c) PreparedStatement
d) ResultSet
Answer: a) CallableStatement
a) WebRowSet
b) SqlRowSet
c) DataRowSet
d) CacheRowSet
Answer: a) WebRowSet
a) A ResultSet
b) The number of rows affected
c) The SQL query executed
d) A boolean value
JDBC Programming
Page 32
19. Which method in the Connection interface is used to start a transaction in JDBC?
a) setAutoCommit(false)
b) commit()
c) rollback()
d) setTransactionIsolation()
Answer: a) setAutoCommit(false)
a) It is a disconnected RowSet.
b) It always works in connected mode.
c) It requires a database connection to fetch data.
d) It is not used for data manipulation.
JDBC Programming
Page 33