AdvanceJava UNIT1.......................
AdvanceJava UNIT1.......................
ADVANCED JAVA
Unit I:
JDBC Programming : JDBC Architecture, Types of JDBC Drivers, Introduction to major JDBC
Classes and Interface, Creating simple JDBC Application, Types of Statement (Statement Interface,
Prepared Statement, Callable Statement), Exploring Result Set Operations, Batch Updates in
JDBC, Creating CRUD Application, Using Rowsets Objects, Managing Database Transaction.
1. JDBC Architecture
2. Types of JDBC Drivers
3. Introduction to major JDBC Classes and Interface
4. Creating simple JDBC Application
5. Types of Statement (Statement Interface, Prepared Statement, Callable Statement)
6. Exploring Result Set Operations
7. Batch Updates in JDBC
8. Creating CRUD Application
9. Using Rowsets Objects
10. Managing Database Transaction.
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
JDBC :
Introduction:
JDBC stands for Java Database Connectivity.
Java Database Connectivity (JDBC) is a Java API(Application Programming Interface) used to
interact with databases. JDBC is a specification from Sun Microsystems and it is used by Java
applications to communicate with relational databases from different vendors. We can use JDBC
to execute queries on various databases and perform operations like SELECT, INSERT, UPDATE
and DELETE.
JDBC API helps Java applications interact with different databases like MSSQL, ORACLE,
MYSQL, etc. It consists of classes and interfaces of JDBC that allow the applications to access
databases and send requests made by users to the specified database.
Purpose of JDBC
Java programming language is used to develop enterprise applications. These applications are
developed with intention of solving real-life problems and need to interact with databases to store
required data and perform operations on it. Hence, to interact with databases there is a need for
efficient database connectivity, ODBC(Open Database Connectivity) driver is used for the same.
ODBC is an API introduced by Microsoft and used to interact with databases. It can be used by
only the windows platform and can be used for any language like C, C++, Java, etc. ODBC is
procedural.
JDBC is an API with classes and interfaces used to interact with databases. It is used only for Java
languages and can be used for any platform. JDBC is highly recommended for Java applications as
there are no performance or platform dependency problems.
We can use JDBC API to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
Key Features of JDBC:
Platform Independence: JDBC can perform database operation on any platform
Standard API: It provides different ways to interact with different databases.
Support for Multiple Databases: JDBC provide support to work with different databases
like MySQL, PostgreSQL, Oracle, etc.
Components of JDBC:
JDBC has four main components that are used to connect with a database as follows:
1. JDBC API
2. JDBC Driver Manager
3. JDBC Test Suite
4. JDBC-ODBC Bridge Drivers
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
1) JDBC API: JDBC API provides various interfaces and methods to establish easy connection
with different databases.
[Link].*;
[Link].*;
3) JDBC Test suite: JDBC Test suite facilitates the programmer to test the various operations such
as deletion, updation, insertion that are being executed by the JDBC Drivers.
4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to connect the database
drivers to the database. The bridge does the translation of the JDBC method calls into the ODBC
method call. It makes the usage of the [Link] package that encompasses the native library
in order to access the ODBC (Open Database Connectivity) characteristics.
Note: Since Java 8, the JDBC-ODBC drivers have been removed. Oracle suggests using drivers
provided by the vendor of the database.
JDBC Architecture:
The JDBC architecture in java is as follows
1. Application
2. The JDBC API
3. DriverManager
4. JDBC Drivers
5. Data Sources
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
1)Application:Applications in JDBC architecture are java applications like applets or servlet that
communicates with databases.
2) The JDBC API: The JDBC API is an Application Programming Interface used to create
Databases.
It allows the Java programs to perform the execution of the SQL statements and then get the
results.
JDBC API uses classes and interfaces to connect with databases. Some of the important classes
and interfaces defined in JDBC architecture in java are the DriverManager class, Connection
Interface, etc.
A few of the crucial interfaces and classes defined in the JDBC API are the following:
o Drivers
o DriverManager
o Statement
o Connection
o CallableStatement
o PreparedStatement
o ResultSet
o SQL data
3) DriverManager: DriverManager plays a crucial role in the architecture of JDBC.
DriverManager class in the JDBC architecture is used to establish a connection between Java
applications and databases. Using the getConnection method of this class a connection is
established between the Java application and data sources.
It uses database-specific drivers to connect the enterprise applications to various databases.
4) JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC
driver which conveniently interacts with the respective data source.
5) Data Sources:
Data Sources in the JDBC architecture are the databases that we can connect using this API. These
are the sources where data is stored and used by Java applications. JDBC API helps to connect
various databases like Oracle, MYSQL, MSSQL, PostgreSQL, etc.
Types of JDBC Architecture
The JDBC Architecture can be of two types based on the processing models it uses. These models
are
1. 2-tier model
2. 3-tier model
2-tier model:
2-tier JDBC architecture model is a basic model.
In this model, a java application communicates directly to the data sources. JDBC driver is
used to establish a connection between the application and the data source.
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
When an application needs to interact with a database, a query is directly executed on the
data source and the output of the queries is sent back to the user in form of results.
In this model, the data source can be located on a different machine connected to the same
network the user is connected to.
This model is also known as a client/server configuration. Here user's machine acts as a
client and the machine on which the database is located acts as a server.
3 Tier Model:
3-tier model is a complex and more secure model of JDBC architecture in java.
In this model the user queries are sent to the middle tier and then they are executed on the
data source.
Here, the java application is considered as one tier connected to the data source(3rd tier)
using middle-tier services.
In this model user queries are sent to the data source using middle-tier services, from where
the commands are again sent to databases for execution.
The results obtained on the database are again sent to the middle-tier and then to the
user/application.
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is
now discouraged because of thin driver.
Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.
The JDBC-Odbc Bridge Driver is found in a package called [Link]. By using this
driver we can develop only 2-tier applications (a Java program and database).
This type of driver is purely implemented in ‘C’ language and this is platform dependent in
nature.
This type-1 driver is used to connect the database with the help of the ODBC API. Hence it
is called a JDBC-ODBC bridge driver.
Advantages
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Disadvantages
The Type-1 driver is very slow, because of JDBC-ODBC transactions.
The Type-1 driver is the dependent driver since its depending on ODBC support.(i.e; The
ODBC bridge driver is needed to be installed in individual client machines.)
The Type-1 driver is not suitable for real-time applications.(i.e; Type-1 driver isn't written
in java, that's why it isn't a portable driver.)
6
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Advantage
Native-API driver gives better performance than JDBC-ODBC bridge driver.(faster)
More secure compared to the type-1 driver.
Disadvantages
The Type-2 driver is both platform and database dependent. Hence it is not suitable for
real-time applications.
This driver is slower than the Type-3 and Type-4 drivers.
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
like auditing, load balancing, logging etc.
Switch facility to switch over from one database to another database.
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
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.
4. Thin Driver - Type 4 Driver (Fully Java Driver)
Type-4 drivers are supplied by Oracle Corporation by developing into Java language.
OracleDriver is the name of Type-4 driver which is released by Oracle Corporation in the
form of [Link].
In order to work with the Type-4 driver, we need to add the [Link] to our classpath.
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.
It is a pure Java driver because it completely implemented by the Java programming
language
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.
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
1. Load the Driver: Driver helps to make a connection to the database hence driver must be
loaded once in the program. This can be done by two methods:
[Link](): By using this, the driver’s class file is loaded in the memory during run
time. There is no need to create a new object.
For example: [Link]("[Link]");// oracle database
[Link](" [Link] "); // mysql database
[Link](): Here DriverManager is an inbuilt Java class where the
register is its static member. By using this, the constructor of the driver class is called
during compile time. In this new object is created.
For example: [Link](new [Link]());
NOTE: If you are using JDBC 4.0 or higher: Since JDBC 4.0,you do not need to call
[Link]() explicitly if the driver JAR us present in classpath- driver auto loading works.
2. Creating Connections: After the driver is loaded, the connection is set up. The connection
object uses username, password, and URL to set up the connection. URL has a predefined format
which contains database name, the driver used, IP address where the database is stored, Port
number and the service provider.
10
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Result:
import [Link].*;
public class JdbcConn
{
public static void main(String[] args) throws SQLException
{
//[Link] connection with getConnection
Connection con = [Link]("jdbc:mysql://localhost:3306", "root", "root");
// 2. Create a Statement object
Statement stmt = [Link]();
Result:
12
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Result:
13
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Implementation: Once the Statement object is created, there are three ways to execute it.
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.
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.
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.
Example:
// Java Program illustrating Create Statement in JDBC
import [Link].*;
public class Program3
{
public static void main(String[] args) throws SQLException
{
// [Link]("[Link]");
// Establish JDBC connection and create statement
Connection con =
[Link]("jdbc:mysql://localhost:3306/mydatabase", "root", "root");
// Close resources
[Link]();
[Link]();
}
}
14
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Result:
2. Prepared Statement
A PreparedStatement 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.
Prepared Statement will improve the performance of the application, because query is compiled
only once.
Syntax:
PreparedStatement pstmt = [Link](query);
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL statements such
as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and set the values in the ? holders,
setABC() of a prepared statement is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
PreparedStatement pstmt = [Link](query);
// where pstmt is an object name
[Link](1,"Ayan");
[Link](2,25);
Implementation: Once the PreparedStatement object is created, there are three ways to execute it:
execute(): This returns a boolean value and executes a static SQL statement that is present
in the prepared statement object.
executeQuery(): This returns a ResultSet from the current prepared statement.
executeUpdate(): This returns the number of rows affected by the DML statements such as
INSERT, DELETE, and more that is present in the current Prepared Statement.
15
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Example:
//Create Student Table with RollNo, Name, and Address field and insert few records using Prepared
Statement
[Link].*;
public class Example
{
public static void main(String[ ] args)
{
// [Link]("[Link]");
try (Connection conn =
[Link]("jdbc:mysql://localhost:3306/student","root", "root"))
{
String createSQL = "CREATE TABLE IF NOT EXISTS Student1 (" +
"RollNo INT PRIMARY KEY, " +
"Name VARCHAR(100), " +
"Address VARCHAR(255))";
try (PreparedStatementstmt = [Link](createSQL))
{
[Link]();
[Link]("Student table created.")
}
String insertSQL = "INSERT INTO Student (RollNo, Name, Address) VALUES (?, ?, ?)";
try (PreparedStatementstmt = [Link](insertSQL))
{
[Link](1, 1);
[Link](2, "Alice Johnson");
[Link](3, "123 Main St");
[Link]();
[Link](1, 2);
[Link](2, "Bob Smith");
[Link](3, "456 Oak St");
[Link]();
16
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Example2:
//Using PreparedStatement Object display the content of Record.
[Link].*;
publicclass Example2
{
publicstaticvoid main(String[] args)
{
/*
Explanation:
% -8s means print a left-aligned string in a width of 8 characters.
%n adds a newline.
*/
17
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
3. Callable Statement
A CallableStatement is used to execute stored procedures in the database. Stored procedures are
precompiled SQL statements that can be called with parameters. They are useful for executing
complex operations that involve multiple SQL statements.
It is an interface in JDBC API which is used to call the stored procedures form the Java
code. CallableStatement extends PreparedStatement which in turn extends Statement.
Syntax:
CallableStatement cstmt = [Link]("{call ProcedureName(?, ?)}");
{call ProcedureName(?, ?)}: Calls a stored procedure named ProcedureName with
placeholders ? for input parameters.
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.
Stored Procedures:
The [Link] package provides the callable statement interface that contains various
methods to enable you to call database stored procedures.
The CallableStatement interface is derived from the prepared Statement Interface
What is stored procedure?
• Stored procedure is a set of SQL statements to be executed to perform a specific
task on a database.
• Stored procedures are precompiled and stored in the database.
Like dynamic SQL queries , you can pass the parameters to stored procedures. Stored procedures
take 3 types of parameters.
1. IN Parameter(Default)
2. OUT Parameter
3. IN OUT Parameter
1. IN parameter: It is the default parameter type used to provide input values to a
procedure or a function.
2. OUT parameter: It is used to fetch output values from a procedure. No initial value is
provided to an OUT parameter. Its value is set by the procedure and returned.
3. INOUT parameter: It is similar to the OUT parameter except that it is provided with an
initial value that is modified by the procedure and returned.
--When you use the stored procedures to perform database operations, it reduces the network
traffic because instead of sending multiple SQL Statements to a database, a single stored procedure
is executed.
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
A stored procedure can call a stored function A stored function cannot call a stored
within its body. procedure.
A stored procedure can use all DML statements A stored function can only use the SELECT
within its body. statement.
A stored procedure cannot be embedded into A stored function can be embedded into
SELECT/WHERE/HAVING etc. clauses. SELECT/WHERE/HAVING etc. clauses.
CREATE PROCEDURE add_numbers(IN num1 INT, IN num2 INT, OUT result INT)
BEGIN
SET result = num1 + num2;
END //
DELIMITER ;
19
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
// Prepare CallableStatement
CallableStatement stmt = [Link]("{call add_numbers(?, ?, ?)}");
// Set IN parameters
[Link](1, 10);
[Link](2, 20);
// Execute
[Link]();
// Retrieve output
int result = [Link](3);
[Link]("Result: " + result);
} catch (SQLException e)
{
[Link]();
}
}
}
Here,
Use [Link]() methods to retrieve output values (e.g., getInt() for INT).
20
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
// SQL
CREATE PROCEDURE say_hello()
BEGIN
SELECT 'Hello from Procedure!';
END;
//Java code:
CallableStatement stmt = [Link]("{call say_hello()}");
ResultSet rs = [Link]();
while ([Link]()) {
[Link]([Link](1));
}
//Java code:
CallableStatement stmt = [Link]("{call double_number(?)}");
[Link](1, 5);
[Link](1, [Link]);
[Link]();
[Link]("Doubled: " + [Link](1));
NOTE:
Use this for general-purpose access to your database. Useful when you
Statement are using static SQL statements at runtime. The Statement interface
cannot accept parameters.
Use this when you plan to use the SQL statements many times. The
PreparedStatement
PreparedStatement interface accepts input parameters at runtime.
Use this when you want to access the database stored procedures. The
CallableStatement
CallableStatement interface can also accept runtime input parameters.
21
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
while ([Link]())
{
// Process the result set
}
[Link]();
[Link]();
[Link]();
}
catch (SQLException e)
{
[Link](); // Handle the exception
}
22
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Closing the result: Once database operations are completed we need close the connections
related to database here we close the ResultSet connection. By using close method.
Types of ResultSet
There are three different characteristics by which ResultSet types are differentiated
1. Scrollability: Determines whether you can move back and forth in the ResultSet
TYPE_FORWARD_ONLY: Can only move forward through the rows
TYPE_SCROLL_INSENSITIVE: Can move forward and backward but changes
are not reflect ResultSet
TYPE_SCROLL_SENSITIVE: Can move forward and backward but changes are
affect the ResultSet
2. Concurrency: Determines whether you can update the ResultSet
CONCUR_READ_ONLY: Can only read data
CONCUR_UPDATABLE: Allows updates to the ResultSet
3. Holdability: Determines what happens to the ResultSet when a Transaction is committed.
HOLD_CURSORS_OVER_COMMIT: The ResultSet remains open after a
commit
CLOSE_CURSORS_AT_COMMIT: The ResultSet closes after a commit
Category of Methods in Result Set:
The methods of the ResultSet interface can be broken down into three categories −
Navigational methods − Used to move the cursor around.
Get methods − Used to view the data in the columns of the current row being pointed by
the cursor.
Update methods − Used to update the data in the columns of the current row. The updates
can then be updated in the underlying database as well.
Method Description
beforeFirst() used for Positions the cursor before the first row
23
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Method Description
afterLast() used for Positions the cursor after the last row
Method Description
getInt(int columnIndex) used for Retrieves an integer from the specified column
getString(int columnIndex) used for Retrieves a string from the specified column
getDouble(int columnIndex) used for Retrieves a double from the specified column
Method Description
24
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Example:
//[Link] create a students table in work database. Below we provide table structure
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
grade FLOAT
);
INSERT INTO students VALUES
(1, 'Krishna', 87.5),
(2, 'Anjali', 91.2),
(3, 'Ravi', 76.8);
//Program on Result set operations:
import [Link].*;
public class ResultSetExample {
public static void main(String[] args)
{
try (Connection con = [Link] ("jdbc:mysql://localhost:3306", "root", "root");
Statement stmt = [Link]( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
ResultSet rs = [Link]("SELECT * FROM students"); )
{
[Link]("Forward Iteration (next):");
while ([Link]())
{
int id = [Link]("id");
String name = [Link]("name");
float grade = [Link]("grade");
[Link](id + " | " + name + " | " + grade);
}
} catch (SQLException e) {
[Link]();
}
}
}
Output :
Forward Iteration (next):
1 | Krishna | 87.5
2 | Anjali | 91.2
3 | Ravi | 76.8
25
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Example2:
We create a employees table in work database. Below we provide table structure
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
PreparedStatement preparedStatement
= [Link](query);
[Link](1, name);
[Link](2, salary);
[Link]();
String query
= "UPDATE employees SET name = ?, salary = ? WHERE id = ?";
PreparedStatement preparedStatement
= [Link](query);
[Link](1, name);
[Link](2, salary);
[Link](3, id);
[Link]();
}
}
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
[Link](1, id);
[Link]();
[Link]("Record deleted successfully.");
}
[Link]("Select an operation:");
[Link]("1. Insert");
[Link]("2. Update");
[Link]("3. Retrieve");
[Link]("4. Delete");
switch (choice) {
case 1:
[Link]("Enter name:");
case 2:
[Link]("Enter ID to update:");
int idToUpdate = [Link]();
[Link]("Enter new name:");
String nameToUpdate = [Link]();
[Link]("Enter new salary:");
double salaryToUpdate
= [Link]();
updateRecord(connection, idToUpdate,
nameToUpdate, salaryToUpdate);
break;
case 3:
retrieveRecords(connection);
break;
case 4:
[Link]("Enter ID to delete:");
int idToDelete = [Link]();
deleteRecord(connection, idToDelete);
break;
default:
[Link]("Invalid choice.");
break;
}
28
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Now enter option 1, That means you can ready to insert data into database.
29
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Now enter option 2, That means you can ready to update employee data by employee ID
Now enter option 3, That means you can fetch all data from table.
Now enter option 4, That means you can delete an employee details by using employee ID.
30
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Grouping a set of INSERT or, UPDATE or, DELETE commands (those produce update count
value) and execute them at once this mechanism is known as a batch update.
Adding statements to the batch:
The statement, PreparedStatement, and CallableStatement objects hold a list (of commands) to
which you can add related statements (those return update count value) using the addBatch( )
method.
[Link](insert1);
[Link](insert2);
[Link](insert3);
Executing the batch
After adding the required statements, you can execute a batch using the executeBatch() method of
the Statement interface.
[Link]();
Using batch updates, we can reduce the communication overhead and increase the performance of
our Java application.
Note: Before adding statements to the batch you need to turn the auto commit off using
the [Link](false) and, after executing the batch you need to save the changes using
the [Link]() method.
Example:
Assume we have created a table named Sales in the database with the following description:
This Example tries to insert a set of statements into the above mentioned table using batch update.
import [Link];
import [Link];
import [Link];
public class BatchUpdates
{
public static void main(String args[ ])throws Exception
{
//Getting the connection
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb", "root",
"root");
[Link]("Connection established......");
//Creating a Statement object
Statement stmt = [Link]();
//Setting auto-commit false
[Link](false);
//Statements to insert records
String insert1 = "INSERT INTO Dispatches VALUES ('KeyBoard', 'Amith', 'January', 1000,
'Hyderabad')";
31
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
String insert2 = "INSERT INTO Dispatches VALUES ('Earphones', 'SUMITH', 'March', 500,
'Vishakhapatnam')";
String insert3 = "INSERT INTO Dispatches VALUES ('Mouse', 'Sudha', 'September', 200,
'Vijayawada')";
//Adding the statements to batch
[Link](insert1);
[Link](insert2);
[Link](insert3);
//Executing the batch
[Link]();
//Saving the changes
[Link]();
[Link]("Records inserted......");
}
}
Output
Connection established......
Records inserted......
If you verify the contents of the table, you can find the inserted records in it as:
32
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
try
{
String sql = "SELECT column1, column2, column3 FROM table_name WHERE id = ?";
PreparedStatement statement = [Link](sql);
[Link](1, 1);
ResultSet result = [Link]();
if ([Link]()) {
String column1 = [Link]("column1");
String column2 = [Link]("column2");
int column3 = [Link]("column3");
[Link]("Column 1: " + column1);
[Link]("Column 2: " + column2);
[Link]("Column 3: " + column3);
}
}
catch (SQLException e)
{
[Link]();
}
33
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
4. Update a record
To update a record in the database, you will need to use an SQL UPDATE statement and execute it
using the connection object.
try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ? WHERE id =
?";
PreparedStatement statement = [Link](sql);
[Link](1, "new_value1");
[Link](2, "new_value2");
[Link](3, 456);
[Link](4, 1);
[Link]();
[Link]("Record updated.");
} catch (SQLException e) {
[Link]();
}
5. Delete a record
To delete a record from the database, you will need to use an SQL DELETE statement and execute
it using the connection object.
try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = [Link](sql);
[Link](1, 1);
[Link]();
[Link]("Record deleted.");
} catch (SQLException e) {
[Link]();
}
The instance of RowSet is the java bean component because it has properties and a java bean
notification mechanism. It is introduced in JDK5. A JDBC RowSet provides a way to store the
data in tabular form. It makes the data more flexible and easier than a ResultSet. The connection
between the RowSet object and the data source is maintained throughout its life cycle.
RowSets are classified into five categories based on how they are implemented which are listed
namely as below:
JdbcRowSet
CachedRowSet
WebRowSet
FilteredRowSet
JoinRowSet
34
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
The JDBC RowSet interface is a RowSet extension. It's a wrapper for the ResultSet object that
adds some extra features.
Syntax: Declaration of Jdbc RowSet interface
public interface JdbcRowSet
extends RowSet, Joinable
In order to connect RowSet with the database, the RowSet interface provides methods for
configuring Java bean properties which are depicted below:
void setURL(String url):
void setUserName(String user_name):
void setPassword(String password):
Lastly, we just need to create a JdbcRowSet object where a sample is shown below illustration as
follows:
Illustration:
JdbcRowSetrowSet = [Link]().createJdbcRowSet();
// 4. Query
[Link]("select * from Students");
35
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
// Importing database
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// Main class
class RowSetDemo {
// Creating a RowSet
JdbcRowSetrowSet = [Link]()
.createJdbcRowSet();
// Creating a query
[Link]("select * from Student");
36
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
Output:
RollNo: 1
Name: jack
Marks: 92
RollNo: 2
Name: jenny
Marks: 90
RollNo: 3
Name: mark
Marks: 80
RollNo: 4
Name: joe
Marks: 82
EXAMPLE2:
Step: Table set up
//SQL
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
grade FLOAT
);
import [Link];
import [Link];
import [Link];
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
while ([Link]()) {
[Link]("Name: " + [Link]("name") + ", Grade: " +
[Link]("grade"));
}
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Requirements
1. JAR dependency for [Link]:
xml
<dependency>
<groupId>[Link]</groupId>
<artifactId>rowset</artifactId>
<version>1.0.1</version>
</dependency>
2. Add mysql-connector-java to your classpath.
Output:
ID | Name | Grade
------------------------
1 | Krishna | 88.50
2 | Anjali | 92.30
3 | Ravi | 79.40
39
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.
Method Description
//simple JDBC program that shows how to manage transactions using setAutoCommit(false),
commit(), and rollback().
Step1: SQL Table
CREATE TABLE bank (
acc_no INT PRIMARY KEY,
name VARCHAR(50),
balance DOUBLE
);
40
SIR CRRCOE
ADVANCED JAVA-R23 DEPARTMENT OF INFORMATION TECHNOLOGY
try {
// Debit ₹100 from Account A
PreparedStatement debit = [Link](
"UPDATE bank SET balance = balance - 100 WHERE acc_no = 1");
[Link]();
}
catch (SQLException e)
{
[Link](); // Rollback if any error
[Link]("Transaction failed. Rolled back.");
[Link]();
}
}
catch (SQLException e)
{
[Link]();
}
}
}
41
SIR CRRCOE