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

Java Unit1

This document provides an overview of Swing and JDBC in Java. It defines Swing as a graphical user interface framework that is part of Java Foundation Classes. Swing components are lightweight, platform independent, and support pluggable look and feel. The document also describes the JDBC API which provides a standard interface for connecting to different database types from Java applications. JDBC uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java Unit1

This document provides an overview of Swing and JDBC in Java. It defines Swing as a graphical user interface framework that is part of Java Foundation Classes. Swing components are lightweight, platform independent, and support pluggable look and feel. The document also describes the JDBC API which provides a standard interface for connecting to different database types from Java applications. JDBC uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

ADVANCE JAVA

UNIT 1

By Shivani Deopa
SWING
What is JFC and AWT?
• The Java Foundation Classes are a graphical framework for building
portable Java-based graphical user interfaces. JFC consists of the
Abstract Window Toolkit, Swing and Java 2D.
• Abstract Window Toolkit (AWT) is a set of application program
interfaces ( API s) used by Java programmers to create graphical user
interface ( GUI ) objects, such as buttons, scroll bars, and windows.
What is Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. Swing components facilitate efficient graphical user
interface (GUI) development.
• Swing Components are collection of lightweight visual components they contain
replacement for heavyweight AWT components as well as complex user-interface
components such as tables and tress.
• Components contain a pluggable look and feel (PL&F) that allows application to
run with native look and feel on different platforms. PL&F allows application to
have the same behaviour on various platform. JFC contains operating system
neutral look and feel.
• Swing component do not contain peers. Swing components allow mixing of AWT
heavyweight and swing light weight components in an application. Heavyweight
components have opaque pixels and are always rectangular whereas lightweight
components have transparent pixels and are non-regular.
Features of Swing:
1. Platform Independent: It is platform independent, the swing components
that are used to build the program are not platform specific. It can be used at
any platform and anywhere.
2. Lightweight: Swing components are lightweight which helps in creating
the UI lighter. Swings component allows it to plug into the operating system
user interface framework that includes the mappings for screens or device
and other user interactions like key press and mouse movements.
3. Plugging: It has a powerful component that can be extended to provide
the support for the user interface that helps in good look and feel to the
application. It refers to the highly modular-based architecture that allows it
to plug into other customized implementations and framework for user
interfaces. Its components are imported through a package called java.swing.
4. Manageable: It is easy to manage and configure. Its mechanism and
composition pattern allows changing the settings at run time as well.
The uniform changes can be provided to the user interface without
doing any changes to application code.
5. MVC: They mainly follows the concept of MVC that is Model View
Controller. With the help of this, we can do the changes in one
component without impacting or touching other components. It is
known as loosely coupled architecture as well.
6. Customizable: Swing controls can be easily customized. It can be
changed and the visual appearance of the swing component
application is independent of its internal representation.
Difference Between AWT and Swing
AWT Swing
AWT components are platform-dependent Java swing components are platform-independent.

AWT components are heavyweight. Swing components are lightweight.


AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful components such
as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.
Component Hierarchy
• JComponent Class is the root of visual
component class hierarchy in JFC.
• The visual components are known as the
“J” classes. The functionality contained in
the JComponent class is available to all the
visual components contained in the JFC.
• The JComponent class is repository of
functionality for all visual component. The
JComponent class is at the top of the
hierarchy of all visual components
contained in the JFC.
• The hierarchy is shown in the following
figure
Types of Panes
• There are 4 types of panes
• RootPane
• GlassPane
• ContentPane
• LayeredPane
What is RootPane, GlassPane and ContentPane?
• When you look at any window in a computer, the outer part containing the
minimize, restore and close buttons and the overall border can be thought of as a
frame. The frame that we are imaging is still hollow!
• That means there is nothing in the middle. So, the frame is similar to a real-life
photo frame.
• When we create a JFrame object, a JRootPane is automatically created and it
occupies the empty part of the frame. So, the JRootPane is like the base of the
photo frame. This means that all the content in the frame should lie on top of it.
• Now the JRootPane has two children. There is an optional MenuBar and a
ContentPane.
• The menu bar occupies the upper part while the rest of the part is used by the
ContentPane.
• As the name suggests, all the contents that we might add will be placed on the
ContentPane. Hence, the ContentPane is very similar to the photograph in the
photo frame.
• It holds the visible content. Whenever we add a component to a JFrame using a
method like frame.add(component), the ContentPane is implicitly called and the
component is added to it.
• As the ContentPane has no default layout, the component takes up the entire
area of the component pane. In case we add a new component, the old
component is overlapped by the new one.
• Finally, we have the GlassPane. It covers the entire visible area of the root pane. It
behaves just like a sheet of glass and is completely transparent unless we
implement the glass pane’s paintComponent method. The glass pane can also
perform complex tasks like intercepting the mouse pointer etc.
• It is similar to the glass on the photo frame which is invisible and lies on top of
the photograph.
• We can summarize this discussion as follows. The JFrame object has a RootPane
at its middle. This root pane acts as a base for the MenuBar and the ContentPane.
All the content is placed on this content pane.
• Finally, a transparent GlassPane covers the entire visible area of the RootPane.
What are LayeredPane?
• A layered pane is a Swing container
which is used to hold the various
• components using the concept of
layers. The components present in
the upper layer overlaps the
components present in the lower
layer.
• The layered pane is created using
the JLayeredPane class. the only
constructor of this class is
JLayeredPane ().
Swing Components
• JLabel • JList
• JTextField and JPasswordField • JScrollPane
• JTextAres • JTable
• JButton • JTabbedPane
• JCheckBox • JMenu
• JRadioButton • JTree
• JComboBox
JDBC
Introduction to JDBC
• 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.
1. Making a connection to a database.
2. Creating SQL or MySQL statements.
3. Executing SQL or MySQL queries in the database.
4. Viewing & Modifying the resulting records.
• 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 −
a) Java Applications
b) Java Applets
c) Java Servlets
d) Java ServerPages (JSPs)
e) 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.
Characteristics of JDBC
• It is a call-level SQL interface for java
• It does not restrict the type of queries passed to an underlying DBMS
Driver
• JDBC mechanism are simple to understand and use
• It provides a java interface that stays consistent with the rest of the
Java system
• JDBC may be implemented on top of common level APIs(Application
Program Interface).
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 −
2-Tire Architecture
• In the two-tier model, a Java application talks
directly to the data source.
• This requires a JDBC driver that can communicate
with the particular data source being accessed.
• A user's commands are delivered to the database
or other data source, and the results of those
statements are sent back to the user.
• The data source may be located on another
machine to which the user is connected via a
network.
• This is referred to as a client/server configuration,
with the user's machine as the client, and the
machine housing the data source as the server.
3-Tire Architecture
• With the introduction of optimizing compilers that
translate Java bytecode into efficient machine-specific
code and technologies such as Enterprise JavaBeans, the
Java platform is fast becoming the standard platform for
middle-tier development.
• This is a big plus, making it possible to take advantage of
Java's robustness, multithreading, and security features.
• With enterprises increasingly using the Java programming
language for writing server code, the JDBC API is being
used more and more in the middle tier of a three-tier
architecture.
• Some of the features that make JDBC a server technology
are its support for connection pooling, distributed
transactions, and disconnected rowsets.
• The JDBC API is also what allows access to a data source
from a Java middle tier.
JDBC Drivers
• JDBC drivers are client-side adapters (installed on the client machine, not
on the server) that convert requests from Java programs to a protocol that
the DBMS can understand. JDBC drivers are the software components
which implements interfaces in JDBC APIs to enable java application to
interact with the database.
• Now we will learn how many JDBC driver types does Sun defines? There
are four types of JDBC drivers defined by Sun Microsystem that are
mentioned below:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver
Type-3 driver or Network Protocol driver
Type-4 driver or Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
• Type-1 driver or 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. 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
• As a common driver is used in order to interact with different databases, the data transferred through
this driver is not so secured.
• The ODBC bridge driver is needed to be installed in individual client machines.
• Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API driver – Type 2 driver ( Partially Java 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, that’s why 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.
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.
3. Network Protocol driver – Type 3 driver (fully Java driver)
• The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. Here all the database connectivity drivers are
present in a single server, hence no need of individual client-side installation.
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.
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 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 varies, then the driver will carry because it is database
dependent.
Connection Modes
• Connection with URL
String url = "jdbc:h2:~/test"; //database specific url.
Connection connection =
DriverManager.getConnection(url);

• Connection with URL, user, password


String url = "jdbc:h2:~/test"; //database specific url.
String user = "sa";
String password = "";
Connection connection =
DriverManager.getConnection(url, user, password);
• Connection via Try-With- • Connection With URL and
Resources Properties
String url = "jdbc:h2:~/test"; String url = "jdbc:h2:~/test";
//database specific url. //database specific url.
String user = "sa";
String password = ""; Properties properties = new
Properties( );
try(Connection connection = properties.put( "user", "sa" );
DriverManager.getConnection(url, properties.put( "password", "" );
user, password)) {
Connection connection =
//use the JDBC Connection inhere DriverManager.getConnection(url,
} properties);
• Steps to Connect Java Application with Database
Step 1 – Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections
Step 1: Import the Packages

Step 2: Loading the drivers


• In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one
of two ways mentioned below as follows:

2-A Class.forName()
• Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:
Class.forName(“com.mysql.jdbc.Driver”);
2-B DriverManager.registerDriver()
• DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
• After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
a) user: Username from which your SQL command prompt can be accessed.
b) password: password from which the SQL command prompt can be
accessed.
c) con: It is a reference to the Connection interface.
d) Url: Uniform Resource Locator which is created as shown below:
String url = “jdbc:mysql://localhost/empdetails”

• Where oracle is the database used, thin is the driver used, @localhost is
the IP Address where a database is stored,empdetails is the database
name. All 3 parameters above are of String type and are to be declared by
the programmer before calling the function. Use of this can be referred to
form the final code.
Step 4: Create a statement
• Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you
to send SQL commands and receive data from your database.
• Use of JDBC Statement is as follows:
Statement st = con.createStatement();

Step 5: Execute the query


• Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as follows:
a) The query for updating/inserting a table in a database.
b) The query for retrieving data.
• The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that can
be used to get all the records of a table.
• The executeUpdate(sql query) method of the Statement interface is used to execute
queries of updating/inserting.
Types of Statements in JDBC
• The statement interface is used to create SQL basic statements in Java
it provides methods to execute queries with the database.
• There are different types of statements that are used in JDBC as
follows:
1. Create Statement
2. Prepared Statement
3. Callable Statement
1. Create a Statement: From the connection interface, you can create the
object for this interface. It is generally used for general–purpose access to
databases and is useful while using static SQL statements at runtime.
Syntax: Statement statement = connection.createStatement();

• Implementation: Once the Statement object is created, there are three


ways to execute it.
1. boolean execute(String SQL): If the ResultSet object is retrieved, then it
returns true else false is returned. Is used to execute SQL DDL statements
or for dynamic SQL.
2. int executeUpdate(String SQL): Returns number of rows that are
affected by the execution of the statement, used when you need a
number for INSERT, DELETE or UPDATE statements.
3. ResultSet executeQuery(String SQL): Returns a ResultSet object. Used
similarly as SELECT is used in SQL.
import java.sql.*;
class StatementDemo {
public static void main(String[] args){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
Statement statement = con.createStatement();
String sql = "select * from people";
ResultSet result = statement.executeQuery(sql);
while (result.next())
{
System.out.println( "Name: " + result.getString("name"));
System.out.println( "Age:" + result.getString("age"));
}
}
catch (SQLException e) { System.out.println(e); }
}
}
2. Prepared Statement represents a recompiled SQL statement, that can be executed many times. This
accepts parameterized SQL queries. In this, “?” is used instead of the parameter, one can pass the
parameter dynamically by using the methods of PREPARED STATEMENT at run time.
• 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, setXXX()
of a prepared statement is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
Prepared Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
• Implementation: Once the PreparedStatement object is created, there are three ways to execute it:
a) execute(): This returns a boolean value and executes a static SQL statement that is present in the
prepared statement object.
b) executeQuery(): Returns a ResultSet from the current prepared statement.
c) executeUpdate(): Returns the number of rows affected by the DML statements such as INSERT,
DELETE, and more that is present in the current Prepared Statement.
3. Callable Statement are stored procedures which are a group of statements
that we compile in the database for some task, they are beneficial when we
are dealing with multiple tables with complex scenario & rather than sending
multiple queries to the database, we can send the required data to the stored
procedure & lower the logic executed in the database server itself.
The Callable Statement interface provided by JDBC API helps in executing
stored procedures.
Syntax: To prepare a CallableStatement
CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");

• Implementation: Once the callable statement object is created


a) execute() is used to perform the execution of the statement.
ResultSet
• The SQL statements that read data from a database query, return the data
in a result set.
• The SELECT statement is the standard way to select rows from a database
and view them in a result set.
• The java.sql.ResultSet interface represents the result set of a database
query.
• A ResultSet object maintains a cursor that points to the current row in the
result set.
• The term "result set" refers to the row and column data contained in a
ResultSet object.
Generating a ResultSet
• First, we retrieve a ResultSet by calling executeQuery() on any object implementing the
Statement interface. Both the PreparedStatement and the CallableStatement are
subinterfaces of Statement:
PreparedStatement pstmt = dbConnection.prepareStatement("select * from emp");
ResultSet rs = pstmt.executeQuery();
• The ResultSet object maintains a cursor that points to the current row of the result set.
We’ll use next() on our ResultSet to iterate through the records.
• Next, we’ll use the getX() methods while iterating through the results to fetch the values
from the database columns, where X is the datatype of the column. In fact, we’ll provide
database column names to the getX() methods:
while(rs.next()) {
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
}
Navigating the ResultSet
• When we obtain a ResultSet, the position of the cursor is before the first row. Moreover, by
default, the ResultSet moves only in the forward direction. But, we can use a scrollable
ResultSet for other navigation options.
• ResultSet Types
• ResultSet type indicates how we’ll steer through the dataset:
1. TYPE_FORWARD_ONLY – the default option, in which the cursor moves from start to end
2. TYPE_SCROLL_INSENSITIVE – our cursor can move through the dataset in both forward
and backward directions; if there are changes to the underlying data while moving
through the dataset, they are ignored; the dataset contains the data from the time the
database query returns the result
3. TYPE_SCROLL_SENSITIVE – similar to the scroll insensitive type, however for this type, the
dataset immediately reflects any changes to the underlying data
• Not all databases support all the ResultSet types. So, let’s check if the type is supported by
using the supportsResultSetType on our DatabaseMetaData object:
DatabaseMetaData dbmd = dbConnection.getMetaData();
boolean isSupported =
dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
Scrollable ResultSet
• To get a scrollable ResultSet, we need to pass some additional
parameters while preparing the Statement.
• For example, we would obtain a scrollable ResultSet by using either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE as a ResultSet
type:
PreparedStatement pstmt = dbConnection.prepareStatement(
"select * from employees",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt.executeQuery();
• Navigation Options
• We can use any of the below options on a scrollable ResultSet:
1. next() – proceeds to the next row from the current position
2. previous() – traverses to the previous row
3. first() – navigates to the first row of the ResultSet
4. last() – jumps to the last row
5. beforeFirst() – moves to the start; calling next() on our ResultSet after
calling this method returns the first row from our ResultSet
6. afterLast() – leaps to the end; calling previous() on our ResultSet after
executing this method returns the last row from our ResultSet
7. relative(int numOfRows) – go forward or backward from the current
position by the numOfRows
8. absolute(int rowNumber) – jumps to the rowNumber specified
• Let’s see some examples:
PreparedStatement pstmt = dbConnection.prepareStatement(
"select * from employees",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) { // iterate through the results from first to last }
rs.beforeFirst(); // jumps back to the starting point, before the first row
rs.afterLast(); // jumps to the end of resultset
rs.first(); // navigates to the first row
rs.last(); // goes to the last row
rs.absolute(2); //jumps to 2nd row
rs.relative(-1); // jumps to the previous row
rs.relative(2); // jumps forward two rows
while (rs.previous()) { // iterates from current row to the first row in backward direction
}
ResultSet Row Count
• Let’s use getRow() to get the current row number of our ResultSet.
• First, we’ll navigate to the last row of the ResultSet and then use
getRow() to get the number of records:

rs.last();
int rowCount = rs.getRow();
Updating Data in a ResultSet
• By default, the ResultSet is read-only. However, we can use an updatable
ResultSet to insert, update, and delete the rows.
• ResultSet Concurrency
• The concurrency mode indicates if our ResultSet can update the data.
• The CONCUR_READ_ONLY option is the default and should be used if we don’t
need to update the data using our ResultSet.
• However, if we need to update the data in our ResultSet, then the
CONCUR_UPDATABLE option should be used.
• Not all databases support all the concurrency modes for all ResultSet types.
Therefore, we need to check if our desired type and concurrency mode are
supported using the supportsResultSetConcurrency() method:

DatabaseMetaData dbmd = dbConnection.getMetaData();


boolean isSupported = dbmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
• Obtaining an Updatable ResultSet
• To obtain an updatable ResultSet, we need to pass an additional
parameter when we prepare the Statement. For that, let’s use
CONCUR_UPDATABLE as the third parameter while creating a
statement:

PreparedStatement pstmt = dbConnection.prepareStatement(


"select * from employees",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt.executeQuery();
• Updating a Row
• In this section, we’ll update a row using the updatable ResultSet
created in the previous section.
• We can update data in a row by calling updateX() methods, passing
the column names and values to update. We can use any supported
data type in place of X in the updateX() method.
• Let’s update the “salary” column, which is of type double:
rs.updateDouble("salary", 1100.0);
• Note that this just updates the data in the ResultSet, but the
modifications are not yet saved back to the database.
• Finally, let’s call updateRow() to save the updates to the database:
rs.updateRow();
• Inserting a Row
• Now, let’s insert a new row using our updatable ResultSet.
• First, we’ll use moveToInsertRow() to move the cursor to insert a new row:
rs.moveToInsertRow();
• Next, we must call updateX() methods to add the information to the row. We need to
provide data to all the columns in the database table. If we don’t provide data to every
column, then the default column value is used:
rs.updateString("name", "Venkat");
rs.updateString("position", "DBA");
rs.updateDouble("salary", 925.0);
• Then, let’s call insertRow() to insert a new row into the database:
rs.insertRow();
• Finally, let’s use moveToCurrentRow(). This will take the cursor position back to the row
we were at before we started inserting a new row using the moveToInsertRow() method:
rs.moveToCurrentRow();
• Deleting a Row
• In this section, we’ll delete a row using our updatable ResultSet.
• First, we’ll navigate to the row we want to delete. Then, we’ll call the
deleteRow() method to delete the current row:
rs.absolute(2);
rs.deleteRow()
Savepoint
• A Savepoint object is used to save the current state of the database which can be
rolled-back afterwards to that state of the database. Savepoints are similar to the SQL
Transactions and are generally to rollback if something goes wrong within the current
transaction.
• The connection.setSavepoint() method of Connection interface in Java is used to create
an object which references a current state of the database within the transaction.
• The following example shows the usage of Savepoint and Rollback in JDBC application.
Syntax: connection.setSavepoint()
• Returns: It returns a new Savepoint object.
a) setSavepoint(String savepointName): Defines a new savepoint. It also returns a
Savepoint object.
b) 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.
try{ //Submit a malformed SQL
//Assume a valid connection object statement that breaks
conn String SQL = "INSERTED IN
conn.setAutoCommit(false); Employees VALUES (107, 22, 'Sita',
'Tez')";
Statement stmt =
conn.createStatement(); stmt.executeUpdate(SQL);
//set a Savepoint // If there is no error, commit the
changes.
Savepoint savepoint1 =
conn.setSavepoint("Savepoint1"); conn.commit();
String SQL = "INSERT INTO }catch(SQLException se){
Employees VALUES (106, 20, 'Rita', // If there is any error.
'Tez')"; conn.rollback(savepoint1);
stmt.executeUpdate(SQL); }
Batch Updation
• Batch Processing allows you to group related SQL statements into a batch and
submit them with one call to the database.
• When you send several SQL statements to the database at once, you reduce the
amount of communication overhead, thereby improving performance.
• The addBatch() method of Statement,
PreparedStatement, and CallableStatement is used to add individual statements
to the batch. The executeBatch() is used to start the execution of all the
statements grouped together.
• The executeBatch() returns an array of integers, and each element of the array
represents the update count for the respective update statement.
• Just as you can add statements to a batch for processing, you can remove them
with the clearBatch() method. This method removes all the statements you
added with the addBatch() method. However, you cannot selectively choose
which statement to remove.
Example of Batch Processing with Statement Object
Statement stmt = conn.createStatement();
conn.setAutoCommit(false);
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Zia', 'Ali', 30)";
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
stmt.addBatch(SQL);
// Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
Example of Batch Processing with PreparedStatement Object
String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(?, ?, ?, ?)";
PreparedStatemen pstmt = conn.prepareStatement(SQL);
conn.setAutoCommit(false);
// Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
pstmt.addBatch();
// Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
pstmt.addBatch();
//Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
BLOB & CLOB
• Blob and Clob together are known as LOB(Large Object Type). The
following are the major differences between Blob and Clob data
types.
BLOB CLOB
The full form of Blob is a Binary Large Object. The full form of Clob is Character Large Object.

This is used to store large binary data. This is used to store large textual data.

This stores values in the form of binary streams. This stores values in the form of character streams.

Using this you can stores files like videos, images, Using this you can store files like text files, PDF
gifs, and audio files. documents, word documents etc.
BLOB CLOB
MySQL supports this with the following MySQL supports this with the following
datatypes:TINYBLOB datatypes:TINYTEXT
•BLOB •TEXT
•MEDIUMBLOB •MEDIUMTEXT
•LONGBLOB •LONGTEXT
In JDBC API it is represented by java.sql.Blob In JDBC it is represented by java.sql.Clob Interface.
Interface.
The Blob object in JDBC points to the location of BLOB The Blob object in JDBC points to the location of BLOB
instead of holding its binary data. instead of holding its character data.

To store Blob JDBC (PreparedStatement) provides To store Clob JDBC (PreparedStatement) provides methods
methods like:setBlob() like:setClob()
•setBinaryStream() •setCharacterStream()

And to retrieve (ResultSet) Blob it provides methods And to retrieve (ResultSet) Clob it provides methods
like:getBlob() like:getClob()
•getBinaryStream •getCharacterStream()

You might also like