SlideShare a Scribd company logo
1 of 90
ByVikas Jagtap
JDBC
Java DataBase Connectivity
Sun Microsystems has included JDBC API as a part of J2SDK to
develop Java applications that can communicate with
databases.
JDBC Architecture
Java applications cannot directly communicate with a
database to submit data and retrieve the results of queries.
This is because a database can interpret only SQL statements
and not Java language statements.
For this reason, you need a mechanism to translate Java
statements into SQL statements.
The JDBC architecture provides the mechanism for this kind of
translation.
The JDBC architecture can be classified into two layers :
1. JDBC application layer.
2. JDBC driver layer.
1. JDBC application layer : Signifies a Java application that
uses the JDBC API to interact with the JDBC drivers. A JDBC
driver is software that a Java application uses to access a
database. The JDBC driver manager of JDBC API connects
the Java application to the driver.
2. JDBC driver layer : Acts as an interface between a Java
applications and a database. This layer contains a driver ,
such as a SQL server driver or an Oracle driver , which
enables connectivity to a database.
A driver sends the request of a Java application to the
database. After processing the request, the database sends
the response back to the driver. The driver translates and
sends the response to the JDBC API. The JDBC API forwards
it to the Java application.
The following figure shows the JDBC architecture:
Java
application
JDBC API
Driver
Driver
Driver Oracle
SQL
Server
Sybase
JDBC Application Layer JDBC Driver Layer
JDBC Drivers
When you develop JDBC applications, you need to use JDBC
drivers to convert queries into a form that a particular
database can interpret .
The JDBC driver also retrieves the result of SQL statements
and converts the results into equivalent JDBC API class objects
that the Java application uses.
As the JDBC driver only takes care of interactions with the
database, any change made to the database does not affect
the applications.
JDBC supports 4 types of drivers , they are :
1. JDBC-ODBC Bridge driver
2. Native-API Partly-Java driver
3. JDBC-Net Pure-Java driver
4. Native Protocol Pure-Java driver
1. JDBC-ODBC Bridge driver
 The JDBC-ODBC Bridge driver is called the Type 1 driver.
 The JDBC-ODBC Bridge driver converts JDBC calls to Open Database
Connectivity (ODBC) calls.
 The JDBC-ODBC Bridge driver enables a Java applications to use any
databases that supports ODBC driver.
 A Java applications cannot interact directly with the ODBC driver.
 For this reason, the application uses the JDBC-ODBC Bridge driver that
works as an interface between the application and the ODBC driver.
 To use the JDBC-ODBC Bridge driver you need to have the ODBC driver
installed on the client computer.
 The JDBC-ODBC Bridge driver is usually used in stand-alone applications.
JDBC-ODBC Bridge Driver:
Java Application
Type 1 JDBC-ODBC Bridge
ODBC Driver
Database
SQL
Statement Result
The Native-API Partly-Java Driver
 The Native-API Partly-Java driver is called the Type 2 driver.
 It uses the local native libraries provided by the database vendors to access
databases.
 The JDBC driver maps the JDBC calls to the native methods calls, which are
passed to the local native Call Level Interface (CLI). This interface consists
of functions written in C to access databases.
 To use the type 2 driver, CLI needs to be loaded on the client computer.
 As opposed to the JDBC-ODBC Bridge driver, the Native-API Partly-Java
driver does not have an ODBC intermediate layer.
 As a result, this driver has a better performance than the JDBC-ODBC
Bridge driver.
Native-API Partly-Java Driver:
Java Application
Type 2 JDBC Driver
Native Database Library
Database
SQL
Statement
Result
The JDBC-Net Pure-Java Driver
 The JDBC-Net Pure-Java driver is called the Type 3 driver.
 You can use the JDBC-Net Pure-Java driver over the Web while connecting
applets with databases.
 The JDBC-Net Pure-Java driver consists of client and server portions.
 The client portion contains pure Java functions and the server portion
contains Java and native methods.
 The Java applications sends JDBC calls to the JDBC-Net Pure-Java driver
client portion, which in turn , translates JDBC calls into database calls.
 The database calls are sent to the server portion of the JDBC-Net Pure –
Java driver that forwards the request to the database.
 When you use the JDBC-Net Pure-Java driver, CLI native libraries are
loaded on the server.
JDBC-Net Pure-Java Driver:
Java Application
Type 3 JDBC Driver
(Client portion)
Database Server
Type 3 JDBC Driver
(Server Portions)
Native Database Library
Database
SQL Statement Result
The Native-Protocol Pure-Java Driver
 The Native-Protocol Pure-Java driver is called the type 4 driver.
 It is a Java driver that interacts with the database directly using a vendor-
specific network protocol.
 As opposed to the other JDBC driver , you do not require to install any
vendor-specific libraries to use the Type 4 driver.
 DataDirect Technologies provide Type 4 driver for various databases such
as MS SQL Server , AS/400 and DB2.
 This driver is usually used for enterprise applications
Native-Protocol Pure-Java Driver :
Java Application
Type 4 JDBC Driver
SQL Statement Result
Database
JDBC API
The JDBC API classes and interfaces are available in the
java.sql and the javax.sql packages.
The classes and interfaces perform a number of tasks, such as
establish and close a connection with a database , send a
request to a database , retrieve data from a database , and
update data in a database.
The commonly used classes and interfaces in the JDBC API are:
DriverManager class : Loads the driver for the database.
Driver (interface / Class) : Represents a database driver. All
JDBC driver classes must implement the Driver interface.
Connection interface : Enables you to establish a connection
between a Java application and a database.
Statement interface : Enables you to execute SQL statements
ResultSet interface: Represents the information retrieved
from a database.
SQLException class: Provides information about the
exceptions that occur while interacting with databases.
To query a database and display the result using Java
applications , you need to :
1. Load a driver
2. Connect to a database
3. Create and execute JDBC statements
4. Handle SQL exceptions
Loading a Driver
The first step to develop a JDBC application is to load and
register the required driver using the driver manager .
You can load and register a driver :
1. Programmatically :
. Using the forName() method
. Using the registerDriver () method
2. Manually:
. By setting system property
Using the forName () Method
 The forName() method is available in the java.lang.Class
class.
The forName() method loads the JDBC driver and registers the
driver with the driver manager.
The syntax to load a JDBC driver to access a database is :
Class.forName (“driver_name”);
You can load the JDBC-ODBC Bridge driver using the following
method call:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Using the registerDriver () method
 You can create an instance of the Driver class to load a JDBC driver.
 The syntax to declare an instance of the Driver class is :
Driver d = new <driver-name>;
 You can use the following statement to crate an instance of the Driver
class:
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver ();
 Once you have created the Driver object ,call the registerDriver () method
to register it with the DriverManager.
 You can register the JDBC-ODBC Bridge driver using the following method
call to registerDriver () method:
DriverManager.registerDriver (d) ;
Setting System Property
 Driver can also be loaded by setting system property for JDBC drivers.
 You add the driver name to the jdbc.drivers system property to load a
JDBC driver.
 You use the –D command line option to set the system property on the
command line.
 The command to set the system property is :
java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver Demo
 In the preceding command , jdbc.drivers is the property name and
sun.jdbc.odbc.JdbcOdbcDriver is the value that you need to set for the
property.
 After you load a driver , you need to establish the connection with a
database.
Connecting to a Database
 You create an object of the Connection interface to establish a connection
with a database.
 You can create multiple Connection objects in a Java applications to access
and retrieve data from multiple databases.
 The DriverManager class provides the getConnection () to create a
Connection object.
 The getConnection () is an overloaded method that has the following 3
forms:
1. Connection getConnection(String url) :
2. Connection getConnection (String url , String uname ,String pass)
3. Connection getConnection(String url , Properties properties)
String url = “jdbc:odbc:MyDataSource” ;
Connection con = DriverManager.getConnection(url);
The syntax for the JDBC url that is passed as a parameter to the
getConnection() method is :
<protocol>:<subprotocol>:<subname>
1. Protocol name : Indicates the name of the protocol that is used to access
a database. In JDBC, the name of the access protocol is always jdbc .
2. Sub-protocol name : Indicates the mechanism to retrieve data from a
database. For example, if you use the JDBC-ODBC Bridge to access a
database, then the name of the sub protocol is odbc .
3. Subname : Indiacates the Data Source Name (DSN) that contains database
information, such as the name of a database , location of the database
server , user name , and password to access a database server.
String url = “jdbc:odbc:MyDataSource”;
Connection con= DriverManager.getConnection(url,”uname”,”pass”);
String url = “jdbc:odbc:MyDataSource”;
Properties p = new Properties();
p.setProperty(“user” , “Newuser”);
p.setProperty(“password”,”NewPassword”);
Connection con = DriverManager.getConnection(url , p);
After you create a connection ,you need to write JDBC statements
that are to be executed.
Creating and Executing JDBC Statements
 You need to create a Statement object to send requests to and retrieve
results from a database.
 The Connection object provides the createStatement () method to create a
Statement object.
Statement stmt = con.createStatement();
The Statement interface contains the following methods to send static
statements to a database:
1. ResultSet executeQuery (String str) : Executes an SQL statement and
returns a single object of the type , ResultSet. The executeQuery () should
be used when you need to retrieve data from a database table using the
SELECT statement.
Statement stmt = con.createStatement ();
ResultSet rs = stmt.executeQuery(<SQL statement >);
2. int executeUpdate(String str) : Executes the SQL statements and
returns the number of data rows that are affected after processing the
SQL statement. When you need to modify data in a database table using
the DML statements , INSERT, DELETE, and UPDATE you can use the
executeUpdate() .
Statement stmt = con.createStatement ();
ResultSet rs = stmt.executeUpdate(<SQL statement >);
3. boolean execute (String str ) : Executes an SQL statement and returns a
boolean value. You can use this method when the type of SQL statement
passed as parameter is not known or when the statement being executed
returns a result set or an update count. The execute () method returns
true if the of the SQL statement is an object of ResultSet and false if it is
an update count.
Statement stmt = con.createStatement();
stmt.execute(<SQL statement>);
You can use the DML statements , INSERT , UPDATE and DELETE , in Java
applications to modify the data stored in the databasetables.
You can also use the DDL statements, CREATE, ALTER and DROP in java
applications to define or change the structure of database objects.
Querying a Table
String str = “SELECT * from authors” ;
Statement stmt = con.createStatement ();
ResultSet rs = stmt.executeQuery(str);
String str = “SELECT * from authors WHERE city = ‘Pune’ ” ;
Statement stmt = con.createStatement ();
ResultSet rs = stmt.executeQuery(str);
Inserting Rows in a Table
String str = “INSERT INTO authors (au_id, au_lname) VALUES (‘998’,’ABC’)” ;
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
String str = “DELETE FROM authors WHERE lname=‘ABC’ ” ;
String str = “CREATE TABLE MyProduct”
+ “ (p_id INTEGER, ”
+ ”p_name VARCHAR(25), ”
+ “rate FLOAT ,”
+ “unit_msr CHAR (6) )” ;
String str = “ALTER TABLE MyProduct”
+ “ADD quantity INTEGER” ;
String str = “DROP TABLE MyProduct” ;
Handling SQL Exceptions
 The java.sql package provides the SQLException class , which is derived
from the java.lang.Exception class.
 The SQLException is thrown by various methods in the JDBC API and
enables you to determine the reason of the errors that occur while
connecting a Java application to a database.
 You can catch the SQLException in a Java application using the try and
catch exception handling block.
 The methods in the SQLException class are :
1. int getErrorCode () : Returns the error code associated with the
error occurred.
2. String getSQLState() : X/Open error code.
3. SQLException getNextException () : Returns the next exceptions
in the chain of exceptions.
Try
{
String str = “DELETE FROM authors WHERE au_id = ‘123’ ” ;
Statement stmt = con.createStatement();
int count = stmt.executeUpdate (str) ;
}
catch (SQLException sqlexception)
{
System.out.println (“Display Error Code”) ;
System.out.println( “SQL Exception” + sqlexception.getErrorCode ()) ;
}
Result Sets
 When you execute a query to retrieve data from a table using a java
application , the output of the query is stored in a ResultSet object in a
tabular format.
 A ResultSet objects maintains a cursor that enables you to move through
the rows stored in a ResultSet object.
 By Default , the ResultSet object maintains a cursor that moves in the
forward direction only.
 As a result , it moves from the first row to the last row in the ResultSet.
 You cannot update the default ResultSet object.
 The cursor in the ResultSet object initially points before the first row
Type of Results Sets
 Read only : Allows you to only read the rows in a ResultSet object.
 Forward only : Allows you to move the result set cursor from first row to
last row in forward direction only.
 Scrollable : Allows you to move the result set cursor forward or backward
through the result set.
 Updatable : Allows you to update the result set rows retrieved from a
database table.
You can specify the type of a ResultSet object using the createStatement ()
of the Connection interface.
The createStatement() accepts ResultSet fields as parameters to create
different types of the ResultSet objects.
ResultSet fields
 TYPE_SCROLL_SENSITIVE : Specifies that the cursor of the ResultSet
object is scrollable and it reflects the changes in the data made by the
other users.
 TYPE_SCROLL_INSENSITIVE : Specifies that the cursor of the ResultSet
object is scrollable and it does not reflect changes in the data made by the
other users.
 TYPE_FORWARD_ONLY : Specifies that the cursor of the ResultSet object
moves in forward direction only from the first row to the last row.
 CONCUR_READ_ONLY : Specifies the concurrency mode that does not
allow you to update the ResultSet object.
 CONCUR_UPDATABLE : specifies the concurrency mode that allows you to
update the ResultSet object.
 HOLD_CURSORS_OVER_COMMIT : Specifies that a ResultSet object should
not be closed after data is committed to the database.
 CLOSE_CURSORS_AT_COMMIT : Specifies that a Result Set object should
be closed after data is committed to the database.
The createStatement() is an overloaded method that has 3 prototypes.
1. Statement createStatement () : Does not accept any parameter. This
method creates a default ResultSet object that only allows forward
scrolling.
2. Statement createStatement (int , int) : The first parameter indicates the
ResultSet type that determines whether or not , a result set cursor can
move backward. The second parameter indicates the concurrency mode
for the result set that determines whether the data in result set can be
updates . This method creates a ResultSet object with the given type and
concurrency.
3. Statement createStatement (int , int , int ) : In addition to he ResultSet
types and the concurrency mode , this method accepts a third parameter.
This parameter indicates whether or not, the result set is closed after
committing data to the database. This method creates a ResultSet object
with the given type , concurrency and state.
Methods of ResultSet
 boolean first () : Shifts the control of a result set cursor to
the first row of the result set.
 boolean isFirst() : Determines whether the result set cursors
points to the first row of the result set.
 boolean beforeFirst() : Shifts the control of a result set cursor
before the first row of the result set.
 boolean isBeforeFirst () : Determines whether the result set
cursor points before the first row of the result set.
 boolean last() : Shifts the control of a result set cursor to the
last row of the result set.
 boolean isLast () : Determines whether the result set cursor
points to the last row of the result set.
 boolean afterLast() : Shifts the control of a result set cursor after the last
row of the result set.
 boolean isAfterLast () : Determines whether the result set cursor points
after the last row of the result set.
 boolean previous () : Shifts the control of a result set cursoe to the
previous row of the result set.
 boolean absolute (int i) : Shifts the control of a result set cursor to the
row number that you specify as a paramter.
 boolean relative (int i) : Shifts the control of a result set cursor , forward
or backward , relative to he row number that you
specify as a paramter .This method accepts either
a positive or a negative values as a paramter
Statement stmt =
con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(“SELECT * FROM authors”)
if (rs.isBeforeFirst()== true)
System.out.println(“Result set cursor id before first row in result set”);
if (rs.first() == true)
System.out.println(rs.getString(1) + “,” + rs.getString(2)+”,”+rs.getString(3));
System.out.println(“using absolute() method”);
rs.absolute(4);
int rowcount = rs.getRow() ;
System.out.println(“rowNum should be 4 ” + rowcount);
 JDBC allows you to create an updatable result set that enables you to
modify the rows in the result set.
 The following methods used with updatable result set:
1 . void updateRow () : Updates a row of the current ResultSet object and
the underlying database tables.
2. void insertRow () : Inserts a row in the current ResultSet object and
underlying database table.
3. void deleteRow () : Deletes a row from the current ResultSet object and
underlying database table.
4. void updateString () : Updates the specified column with the given string
value.
5. void updateInt() : Updates the specified column with the given int value.
Statement stmt =
con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery
(“SELECT au_id , city , state FROM authors WHERE au_id = ‘123’ ”) ;
rs.next () ;
rs.updateString(“state” , “MAHARASHTRA”) ;
rs.updateString(“city” , “Pune”);
rs.updateRow() ;
Assignment
 Create an application to retrieve information (author id , name , address ,
city and state ) about the authors who are living in the city where the city
name begins with the letter “ P ” .
Don’t use servlet and JSP for this ,USE Simple java program .
PreparedStatement interface
 The PreparedStatement objects accepts the runtime parameters.
 The PreparedStatement interface is derived from the Statement interface
and is available in the java.sql package.
 The PreparedStatement objects are compiled and prepared only once by
JDBC.
 The future invocation of the PreparedStatement object does not recompile
the SQL statements.
 This helps in reducing the load on the database server and thus improving
the performance of the application .
 The PreparedStatement interface inherits the following methods to
execute SQL statement s from the Statement interface:
1. ResultSet executeQuery () : Executes a SELECT statement and returns
the result in a ResultSet object.
2. int executeUpdate(): Executes an SQL statement, INSERT , UPDATE , or
DELETE and returns the count of the rows affected.
3. boolean execute () : Executes an SQL statement and returns a boolean
value.
stat = con.prepareStatement(“SELECT * FROM authors WHERE au_id = ? ”) ;
The SQL statement can contain ‘ ? ‘ symbol as placeholder that can be
replaced by input parameters at runtime.
Before executing the SQL statements specified in the PreparedStatement
object , you must set the value of each ‘ ? ‘ parameter.
This is done by calling an appropriate setXXX () method , where XXX is the
data type of the parameter.
stat.setString (1, “123”);
ResultSet rs = stat.executeQuery ();
 The PreparedStatement interface provides various methods to set the
value of the placeholders for the specific data types.
1. void setByte (int index , byte val) : Sets the java byte type value for
the parameter corresponding to index passed as a parameter.
2. void setBytes (int index , byte[] val) : Sets the Java byte type array
for the parameter corresponding to index passed as a parameter.
3. void setBoolean (int index , boolean val) : Sets the Java boolean type
value for the parameter corresponding to index passed as a parameter.
4. void setDouble (int index, double val) : Sets the Java double type
value value for the parameter corresponding to the index passed as a
parameter.
5. void setInt (int index , int val) : Sets the Java int type value for the
parameter corresponding to index passed as a parameter.
6. void setLong(int index , long val) : Sets the Java long type value for the
parameter corresponding to index passed as a parameter.
7. void setFloat (int index , float val) : Sets the Java float type value for
the parameter corresponding to index passed as a parameter.
8. void setShort (int index , short val) : Sets the Java short type value for
the parameter corresponding to index passed as a parameter.
9. void setString(int index , String val) : Sets the Java String type value for
the parameter corresponding to index passed as a parameter.
Retrieving Rows
String str = “SELECT * FROM titles WHERE au_id = ? ” ;
PreparedStatement ps = con.prepareStatement(str) ;
ps.setString(1 , “101”);
ResultSet rs = ps.executeQuery ();
Inserting Rows
String str =
“ INSERT INTO authors (au_id , au_fname , au_lname) VALUES (? , ? , ? ) ” ;
PreparedStatement ps = con.prepareStatement(str);
ps.setString (1, “101”);
ps.setString (2, “ABC”);
ps.setString (3 , “XYZ”);
int rt = ps.executeUpdate() ;
Updating & Deleting Row
String str = “ UPDATE authors SET state = ? WHERE city = ? “ ;
PreparedStatement ps = con.prepareStatement(str);
ps.setString (1, “MH”);
ps.setString (2, “Pune”);
int rt = ps.executeUpdate() ;
String str = “ DELETE FROM authors WHERE au_fname = ? “ ;
PreparedStatement ps = con.prepareStatement(str);
ps.setString (1, “PPPP”);
int rt = ps.executeUpdate() ;
Transactions
 A transaction is a set of one or more SQL statements that are executed as a
single unit.
 A transaction is complete only when all the SQL statement in a trasaction
execute successfully.
 If any one of the SQL statements in the transaction fails , the entire
transaction is rolled back thereby maintaining consistency of the data in
the database.
 JDBC API provides support for transaction management.
 E.g. : transfer of money from a bank account.
The database transactions can be committed in two ways in
the JDBC applications.
Implicit :
The Connection object uses the auto-commit mode to execute the SQL
statements implicitly.
The auto-commit mode specifies that each SQL statement in a
transaction is committed automatically as soon as the execution of SQL
statement completes.
By default all the transaction statement in a JDBC application are auto-
committed.
Explicit :
For explicitly committing transaction statement in a JDBC application,
you have to use the setAutoCommit () method .
This method accepts either of the two values , true or false , to set or
reset the auto-commit mode for a database. The auto-commit mode is
set to false to commit a transaction explicitly .
You can set the auto-commit mode to false using the following method
call : con.setAutoCommit (false) ;
 When you set the auto-commit mode to false ,the operations performed by
the SQL statement are not reflected permanently in a database.
 You need to explicitly call the commit () method of the Connection
interface to reflect the changes made by the transactions in a database.
 All the SQL statement that appear between two commit() methods are
treated as a single transaction and are executed as a single unit.
 The rollback () method is used to undo the changes made in the database
after the last commit operations.
 You need to explicitly invoke the rollback () method to revert a database in
the last committed state.
 When a rollback () method is invoked , all the pending transactions of a
database are cancelled and the database reverts the state in which it was
committed previously.
 You can call the rollback () method using the following method call :
con.rollback () ;
Batch Updates
 A batch is a group of update statements that are sent to a database to be
executed as a single unit.
 You send the batch to a database in a single request using the same
Connection object.
 This reduces network calls between the application and the database .
 For this reason , processing the multiple SQL statements in a batch is a
more efficient way as compared to the processing of a single SQL
statement.
 A JDBC transaction can comprise of multiple batches.
Implementing Batch Updates in JDBC
 The SQL statements that are part of a batch are called the batchable
statements.
 The Statement or PreparedStatement interface provides following
methods to create and executes a batch of SQL statements :
1. void addBatch () : Adds an SQL statement to a batch .
2. void executeBatch () : Sends a batch of SQL statements to a database
for processing and returns the total number of the rows updated.
3. void clearBatch () : Removes the SQL statements from the batch.
 You can create Statement object to perform batch updates.
 When a Statement object is created an empty array is associated with the
object.
 You can add multiple SQL statements to the empty array to execute them
as a batch.
 You also need to disable the auto-commit mode using
setAutoCommit (false) while working with batch updates in JDBC.
 This enables you to rollback the entire transaction performed using a
batch update if any SQL statement in the batch fails.
con.setAutoCommit (false) ;
Statement stmt = con.createStatement () ;
stmt.addBatch(“INSERT INTO product (p-id , p-desc) VALUES
(1001,’PRINTER’) ”) ;
stmt.addBatch(“INSERT INTO product (p_id , p_desc) VALUES
(1002,’SCANNER’) ”);
The SQL statement in a batch are processed in the order in which the
statements appear in a batch.
int [] updcount = stat.executeBatch () ;
Exception-Handling in Batch Updates
 The batch update operations can throw two types of exceptions ,
SQLException and BatchUpdateException.
 The JDBC API methods, addBatch () or executeBatch () throw the
SQLException when problem occurs while accessing a database.
 The SQLException exception is thrown when you try to execute a SELECT
statement using the executeBatch () method.
 The BatchUpdateException class is derived from SQLException class.
 The BatchUpdateException exception is thrown when the SQL statement in
the batch cannot be executed due to :
1. Presence of illegal arguments in the SQL statement.
2. Absence of the database table.
 The BatchUpdateException uses an array of the update count to identify
the SQL statement that throws the exception.
 The update count for all the SQL statement that are executed successfully
is stored in the array in the same order in which the SQL statement appear
in the batch.
 You can traverse the array of update count to determine the SQL
statement that is not executed successfully in a batch.
 The null value in an array of update count indicates that the SQL
statement in the batch failed to execute.
import java.sql.*;
public class BatchUpdate
{
public static void main (String arg [])
{
try
{
/ * Batch Update Code comes here */
} catch (BatchUpdateException bexp)
{
System.err.println (“SQL Exception :” + bexp.getMessage ()) ;
System.err.println(“Update Counts”) ;
int [] count = bexp.getUPdateCounts();
for (int I = 0 ; i<=count.length ; i++ )
System.err.println(count[i]) ;
}
}
Assignment
 Creating an Application to insert Rows in a Table Using Batch Updates
Stored Procedures
 The java.sql package provides the CallableStatement interface that
contains various methods to enable you to call database stored
procedures.
 The CallableStatement interface is derived form the PreparedStatement
interface.
Creating Stored Procedures
 You can use the executeUpdate () to execute the CREATE PROCEDURE SQL
statement.
 Stored procedures can be of two types , parameterized and non-
parameterized.
 Non – parameterized stored procedure in a JDBC application:
String str = “ CREATE PROCEDURE authors_info”
+ “AS”
+ “SELECT au_id , au_lname , au_fname”
+ ”FROM authors”
+ “WHERE city = ‘Pune’ ”
+ ”ORDER BY au_fname” ;
Statement stmt = con.createStatement () ;
int rt = stmt.executeUpdate (str);
 The Connection object con is used to send the CREATE PROCEDURE SQL
statement to a database.
 When you execute the code , the authors_info stored procedure is created
and stored in the database.
 You can use the following code snippet to create a parameterized stored
procedure.
String str = “ CREATE PROCEDURE authors_info_prmtz
@auth_id varchar(15) , @auth_fname varchar(20) output ,
@auth_lname varchar(20) output , @auth_city varchar(20)
output , @auth_state varchar(20) output ”
+ “AS”
+ “SELECT @auth_fname = au_fname , @auth_lname =
au_lname , @auth_city = city , @auth_state = state ”
+ “ FROM authors ”
+ “ WHERE au_id = @auth_id ” ;
Statement stmt = con.createStatement () ;
int rt = stmt.executeUpdate (str);
 In the preceding code snippet , the authors_info_prmtz stored procedure
is created that accepts author id as parameter and retrieve the
corresponding author information form the database.
 The retrieved information is stored in the OUT parameter.
 The SQL Server 2000 uses output keyword to represent OUT parameters.
 A stored procedure can accepts one or multiple parameters.
 A parameter of a stored procedure can take any of these forms :
1. IN : Refers to the argument that you pass to a stored procedure.
2. OUT : Refers to the return value of a stored procedure.
3. INOUT : Combines the functionality of the IN and OUT parameters. The
INOUT parameter enables you to pass an argument to a stored
procedure. The same parameter can also be used to store a
return value of a stored procedure
When you use the stored procedures to perform database operations, it
reduces network traffic because instead of sending multiple SQL
statements to a database , a single stored procedure is executed.
Calling a Stored Procedure without Parameters
 The Connection interface provides the prepareCall() method that is used
to create the CallableStatement object .
 This object is used to a call a stored procedure of a database .
 The prepareCall () is an overloaded method that has the following 3 forms:
1. CallableStatement prepareCall (String str) : Creates a
CallableStatement object to call a stored procedure. The prepareCall ()
accepts a string as a parameter that contains an SQL statement to call a
stored procedure. You can also specify the placeholders to accept
parameters in the SQL statement.
2. CallableStatement prepareCall(String str , int resSetType , int
resSetConc):
Creates a CallableStatement object that returns ResultSet object that has
the specified result set type and concurrency mode.
The method accepts following 3 parameter :
String object :Contains the SQL statement to call a stored procedure.
The SQL statement can contains one or more parameters.
ResultSet types : Specifies any of the 3 result set types ,
TYPE_FORWARD_ONLY , TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE.
ResultSet concurrency modes :Specifies either of these concurrency
modes , CONCUR_READ_ONLY or CONCUR_UPDATABLE , for
a result set
3. CallableStatement prepareCall (String str , int resSetType , int
resSetConcur , int resSetHoldability) : Creates a CallableStatement
object that returns a ResultSet object . This ResultSet object has the
specified result type, concurrency mode, and constant to set the result set
state.
The syntax to call a stored procedure without parameter is :
{ call <procedure_name> } ;
String str = “ {call authors_info}” ;
CallableStatement cs = con.prepareCall (str) ;
ResultSet rs = cs.executeQuery() ;
while(rs.next())
{
System.out.println(“Author ID :” + rs.getString(1) + “t”);
System.out.println(“Author First Name :” + rs.getString(2) + “t”);
System.out.println(“Author Last Name :” + rs.getString(3) + “t”);
}
Calling a Stored Procedure with Parameters
 The SQL escape syntax is used to call a stored procedure with parameters.
 There are two forms of the SQL escape syntax, one that contains result
parameter and one that does not.
 If the SQL escape syntax contains a result parameter, the result parameter
is used to return a value from a stored procedure.
 The result parameter is an OUT parameter. Other parameters of the SQL
escape syntax can contain IN , OUT , or INOUT parameters.
 The syntax to call a stored procedure with parameter is :
{ call <procedure_name> (?)} ;
 You need to set the value of the IN parameters before the
CallableStatement object executed , otherwise the SQLException is
thrown while processing the stored procedure.
<CallableStatement_object>.setInt(<value>)
 If the stored procedure contains OUT and INOUT parameters, these
parameters should be registered with corresponding JDBC types before a
call to a stored procedures is precessed.
 The JDBC types determine the Java data types that are used in the get
methods while retrieving the values of the OUT and INOUT parameters.
cs.registerOutParameter (1 . Java.sql.Types.STRING) ;
Accepts the position of the placeholder and a constant in the java.sql.Types
class as parameters.
cs.registerOutParameter (1, java.sql.Types.DECIMAL , 3) ;
What for 3rd
Parameter used for ?
import java.sql.*;
public class CallProc
{
public static void main(String arg [])
{
String id , fname , lname , address , city ;
try
{
String str = “ { call authors_info ( ? , ? , ? , ? , ? ) } ” ;
Class.forname (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:DSN”) ;
CallableStatement cs = con.prepareCall (str) ;
// pass IN parameter
cs.setString (1 , “123-456” ) ;
//Register OUT paramter
cs.registerOutParameter(2 , Types.VARCHAR);
cs.registerOutParameter(3 , Types.VARCHAR);
cs.registerOutParameter(4 , Types.VARCHAR);
cs.registerOutParameter(5 , Types.VARCHAR);
// process the Stored procedure
cs.execute () ;
fname = cs.getString(2) ;
lname = cs.getString(3) ;
address = cs.getString(4) ;
city = cs.getString(5) ;
----
-----
----
}
Using METADATA in JDBC
 Metadata is the information about data , such as structure and properties
of a table.
 Employee table that has the name , address , salary , designation and
department columns.
 The metadata of the employee table includes information , such as names
of the columns , data type of each column and constraints to enter data
values in the table columns.
 The JDBC API provides the following 2 metadata interfaces to retrieve the
information about the database and result set :
1 . DatabaseMetaData interface
2 . ResultSetMetaData interface
DatabaseMetaData Interface
 The DatabaseMetaData interface provides the methods that enable you to
determine the properties of a database or RDBMS.
 These properties include names of database tables , database version , SQL
keywords , etc…. .
 You can create an object of DatabaseMetaData using the getMetaData () of
the Connection interface.
DatabaseMetaData dm = con.getMetaData () ;
 The following lists the commonly used methods of the DatabaseMetaData
interface :
 ResultSet getColumns (String catalog , String schema, String tablename
String col_name)
-> Retrieves the information about a column of a database table
that is available in the specified database catalog.
 Connection getConnection ()
-> Retrieves the database connection that creates the
DatabaseMetaData object.
 String getDriverName ()
-> Retrieves the name of the JDBC driver for the
DatabaseMetaData object .
 String getDriverVersion ()
-> Retrieves the version of the JDBC driver.
 ResultSet getPrimaryKeys (String catalog , String schema , String table)
-> Retrieves the information about the primary keys of the
database tables.
 String getURL ()
-> Retrieves the URL of the database
 boolean isReadOnly ()
-> Returns a boolean value that indicates whether the database
is a read only database.
 boolean supportsSavePoints ()
-> Returns a boolean value that indicates whether the database
supports savepoints.
Using ResultMetaData Interface
 The ResultSetMetaData interface contains various methods that enable you
to retrieve information about the data in a result set , such as number of
columns , names of columns and data types of the columns.
 The ResultSet interface provides the getMetaData () method to create an
object of the ResultSetMetaData interface .
ResultSetMetaData rm = rs.getMetaData() ;
 The following lists the commonly used methods of the ResultSetMetaData
interface :
 int getColumnCount () : Returns an integer indicating the total number of
columns in a ResultSet object .
 String getColumnLabel (int col_index) : Retrieves the title of the table
column corresponding to the index passed as a parameter to this method.
 String getColumnName (int col_index) : Retrieves the name of the table
column corresponding to the index passed as a parameter to this method.
 int getColumnType (int col_index) : Retrieves the SQL data type of the
table column corresponding to the index passed as a parameter.
 String getTableName(int col_index) : Retrieves the name of the database
table that contains the column corresponding to the index passed as a
parameter.
 boolean isAutoIncrement (int col_index) : Returns a boolean value that
indicates whether the table column corresponding to the index passed as
a parameter increments automatically.
 boolean isCaseSensitive (int col_index) : Returns a boolean value that
indicates whether the table column corresponding to the index passed as a
parameter is case sensitive.
 boolean isReadOnly (int col_index) : Returns a boolean value that
indicates whether the column in a ResultSet corresponding to the index
passed as a parameter is read only.
 boolean isWritable (int col_index) : Returns a boolean value that
indicates whether ResultSet column corresponding to the index passed as a
parameter is updatable.
Assignment
The Manager of New Publishers publishing company ,
sometimes require the information about the tables of the
database used by the company.
He is not familiar with the SQL statements , therefore , he has
asked you to create an application to determine the total
number of columns and the data types of the columns of a
given table .
The table name has to be specified at the runtime.
The java.sql package
Some commonly used interfaces of the java.sql package are :
1. Statement
2. PreparedStatement
3. CallableStatement
4. Connection
5. ResultSet
6. DatabaseMetaData
7. ResultSetMetaData
The javax.sql Package
The commonly used interface of the javax,sql package is
DataSource
Assignment
1. Create a Java application to insert data in the product table
using the Statement object.
2. Create a Java application that uses scrollable result set to
display information retrieved from the customer table.
3. Create a Java application to perform batch updates. The
application should insert information about a new customer
in the customer table.
Jdbc ppt
Jdbc ppt

More Related Content

What's hot

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptVMahesh5
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...Pallepati Vasavi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 

What's hot (20)

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
JQuery selectors
JQuery selectors JQuery selectors
JQuery selectors
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
Java rmi
Java rmiJava rmi
Java rmi
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 

Viewers also liked (20)

JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc
JdbcJdbc
Jdbc
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
 
Jdbc
JdbcJdbc
Jdbc
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Pyramid web framework
Pyramid web frameworkPyramid web framework
Pyramid web framework
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Spring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariSpring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou Tvari
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Java session16
Java session16Java session16
Java session16
 
Interface result set
Interface result setInterface result set
Interface result set
 

Similar to Jdbc ppt

Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2msafad
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptxBekiTube
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbmsKhyalNayak
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptkingkolju
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
JDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdfJDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdfssuser8878c1
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptxujjwalmatoliya
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and DriversSimoniShah6
 

Similar to Jdbc ppt (20)

Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
JDBC
JDBCJDBC
JDBC
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptx
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
jdbc
jdbcjdbc
jdbc
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
JDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdfJDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc document
jdbc documentjdbc document
jdbc document
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 

More from Vikas Jagtap

ip addressing & routing
 ip addressing & routing ip addressing & routing
ip addressing & routingVikas Jagtap
 
broad band networks
 broad band networks broad band networks
broad band networksVikas Jagtap
 
Simple Network Management Protocol by vikas jagtap
Simple Network Management Protocol by vikas jagtapSimple Network Management Protocol by vikas jagtap
Simple Network Management Protocol by vikas jagtapVikas Jagtap
 
KNOWLEDGE BASE SYSTEMS
KNOWLEDGE  BASE SYSTEMSKNOWLEDGE  BASE SYSTEMS
KNOWLEDGE BASE SYSTEMSVikas Jagtap
 
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtapADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtapVikas Jagtap
 
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapOverview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapVikas Jagtap
 
things which make think ooh!!!!!!!! by vikas jagtap
things which make think ooh!!!!!!!! by vikas jagtapthings which make think ooh!!!!!!!! by vikas jagtap
things which make think ooh!!!!!!!! by vikas jagtapVikas Jagtap
 
Dear son daughter by vikas jagtap
Dear son daughter   by vikas jagtapDear son daughter   by vikas jagtap
Dear son daughter by vikas jagtapVikas Jagtap
 
Double vision by vikas jagtap
Double vision by vikas jagtapDouble vision by vikas jagtap
Double vision by vikas jagtapVikas Jagtap
 
Dubai by vikas jagtap
Dubai by vikas jagtapDubai by vikas jagtap
Dubai by vikas jagtapVikas Jagtap
 
District of maharashtra by vikas jagtap
District of maharashtra by vikas jagtapDistrict of maharashtra by vikas jagtap
District of maharashtra by vikas jagtapVikas Jagtap
 
Cr java concept by vikas jagtap
Cr java  concept by vikas jagtapCr java  concept by vikas jagtap
Cr java concept by vikas jagtapVikas Jagtap
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Animation technique
Animation techniqueAnimation technique
Animation techniqueVikas Jagtap
 
An Introduction to BLUETOOTH TECHNOLOGY
An Introduction to BLUETOOTH TECHNOLOGYAn Introduction to BLUETOOTH TECHNOLOGY
An Introduction to BLUETOOTH TECHNOLOGYVikas Jagtap
 
domain network services (dns)
 domain network services (dns) domain network services (dns)
domain network services (dns)Vikas Jagtap
 
Introduction to networking by vikas jagtap
 Introduction to networking by vikas jagtap Introduction to networking by vikas jagtap
Introduction to networking by vikas jagtapVikas Jagtap
 

More from Vikas Jagtap (20)

ip addressing & routing
 ip addressing & routing ip addressing & routing
ip addressing & routing
 
broad band networks
 broad band networks broad band networks
broad band networks
 
Simple Network Management Protocol by vikas jagtap
Simple Network Management Protocol by vikas jagtapSimple Network Management Protocol by vikas jagtap
Simple Network Management Protocol by vikas jagtap
 
KNOWLEDGE BASE SYSTEMS
KNOWLEDGE  BASE SYSTEMSKNOWLEDGE  BASE SYSTEMS
KNOWLEDGE BASE SYSTEMS
 
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtapADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
 
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapOverview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
 
things which make think ooh!!!!!!!! by vikas jagtap
things which make think ooh!!!!!!!! by vikas jagtapthings which make think ooh!!!!!!!! by vikas jagtap
things which make think ooh!!!!!!!! by vikas jagtap
 
Paradise on earth
Paradise on earthParadise on earth
Paradise on earth
 
Dear son daughter by vikas jagtap
Dear son daughter   by vikas jagtapDear son daughter   by vikas jagtap
Dear son daughter by vikas jagtap
 
Double vision by vikas jagtap
Double vision by vikas jagtapDouble vision by vikas jagtap
Double vision by vikas jagtap
 
Dubai by vikas jagtap
Dubai by vikas jagtapDubai by vikas jagtap
Dubai by vikas jagtap
 
District of maharashtra by vikas jagtap
District of maharashtra by vikas jagtapDistrict of maharashtra by vikas jagtap
District of maharashtra by vikas jagtap
 
Cr java concept by vikas jagtap
Cr java  concept by vikas jagtapCr java  concept by vikas jagtap
Cr java concept by vikas jagtap
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Animation technique
Animation techniqueAnimation technique
Animation technique
 
Amit
AmitAmit
Amit
 
An Introduction to BLUETOOTH TECHNOLOGY
An Introduction to BLUETOOTH TECHNOLOGYAn Introduction to BLUETOOTH TECHNOLOGY
An Introduction to BLUETOOTH TECHNOLOGY
 
Network security
 Network security Network security
Network security
 
domain network services (dns)
 domain network services (dns) domain network services (dns)
domain network services (dns)
 
Introduction to networking by vikas jagtap
 Introduction to networking by vikas jagtap Introduction to networking by vikas jagtap
Introduction to networking by vikas jagtap
 

Recently uploaded

FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesSHIVANANDaRV
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 

Recently uploaded (20)

FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 

Jdbc ppt

  • 2. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.
  • 3. JDBC Architecture Java applications cannot directly communicate with a database to submit data and retrieve the results of queries. This is because a database can interpret only SQL statements and not Java language statements. For this reason, you need a mechanism to translate Java statements into SQL statements. The JDBC architecture provides the mechanism for this kind of translation. The JDBC architecture can be classified into two layers : 1. JDBC application layer. 2. JDBC driver layer.
  • 4. 1. JDBC application layer : Signifies a Java application that uses the JDBC API to interact with the JDBC drivers. A JDBC driver is software that a Java application uses to access a database. The JDBC driver manager of JDBC API connects the Java application to the driver. 2. JDBC driver layer : Acts as an interface between a Java applications and a database. This layer contains a driver , such as a SQL server driver or an Oracle driver , which enables connectivity to a database. A driver sends the request of a Java application to the database. After processing the request, the database sends the response back to the driver. The driver translates and sends the response to the JDBC API. The JDBC API forwards it to the Java application.
  • 5. The following figure shows the JDBC architecture: Java application JDBC API Driver Driver Driver Oracle SQL Server Sybase JDBC Application Layer JDBC Driver Layer
  • 6. JDBC Drivers When you develop JDBC applications, you need to use JDBC drivers to convert queries into a form that a particular database can interpret . The JDBC driver also retrieves the result of SQL statements and converts the results into equivalent JDBC API class objects that the Java application uses. As the JDBC driver only takes care of interactions with the database, any change made to the database does not affect the applications.
  • 7. JDBC supports 4 types of drivers , they are : 1. JDBC-ODBC Bridge driver 2. Native-API Partly-Java driver 3. JDBC-Net Pure-Java driver 4. Native Protocol Pure-Java driver
  • 8. 1. JDBC-ODBC Bridge driver  The JDBC-ODBC Bridge driver is called the Type 1 driver.  The JDBC-ODBC Bridge driver converts JDBC calls to Open Database Connectivity (ODBC) calls.  The JDBC-ODBC Bridge driver enables a Java applications to use any databases that supports ODBC driver.  A Java applications cannot interact directly with the ODBC driver.  For this reason, the application uses the JDBC-ODBC Bridge driver that works as an interface between the application and the ODBC driver.  To use the JDBC-ODBC Bridge driver you need to have the ODBC driver installed on the client computer.  The JDBC-ODBC Bridge driver is usually used in stand-alone applications.
  • 9. JDBC-ODBC Bridge Driver: Java Application Type 1 JDBC-ODBC Bridge ODBC Driver Database SQL Statement Result
  • 10. The Native-API Partly-Java Driver  The Native-API Partly-Java driver is called the Type 2 driver.  It uses the local native libraries provided by the database vendors to access databases.  The JDBC driver maps the JDBC calls to the native methods calls, which are passed to the local native Call Level Interface (CLI). This interface consists of functions written in C to access databases.  To use the type 2 driver, CLI needs to be loaded on the client computer.  As opposed to the JDBC-ODBC Bridge driver, the Native-API Partly-Java driver does not have an ODBC intermediate layer.  As a result, this driver has a better performance than the JDBC-ODBC Bridge driver.
  • 11. Native-API Partly-Java Driver: Java Application Type 2 JDBC Driver Native Database Library Database SQL Statement Result
  • 12. The JDBC-Net Pure-Java Driver  The JDBC-Net Pure-Java driver is called the Type 3 driver.  You can use the JDBC-Net Pure-Java driver over the Web while connecting applets with databases.  The JDBC-Net Pure-Java driver consists of client and server portions.  The client portion contains pure Java functions and the server portion contains Java and native methods.  The Java applications sends JDBC calls to the JDBC-Net Pure-Java driver client portion, which in turn , translates JDBC calls into database calls.  The database calls are sent to the server portion of the JDBC-Net Pure – Java driver that forwards the request to the database.  When you use the JDBC-Net Pure-Java driver, CLI native libraries are loaded on the server.
  • 13. JDBC-Net Pure-Java Driver: Java Application Type 3 JDBC Driver (Client portion) Database Server Type 3 JDBC Driver (Server Portions) Native Database Library Database SQL Statement Result
  • 14. The Native-Protocol Pure-Java Driver  The Native-Protocol Pure-Java driver is called the type 4 driver.  It is a Java driver that interacts with the database directly using a vendor- specific network protocol.  As opposed to the other JDBC driver , you do not require to install any vendor-specific libraries to use the Type 4 driver.  DataDirect Technologies provide Type 4 driver for various databases such as MS SQL Server , AS/400 and DB2.  This driver is usually used for enterprise applications
  • 15. Native-Protocol Pure-Java Driver : Java Application Type 4 JDBC Driver SQL Statement Result Database
  • 16. JDBC API The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages. The classes and interfaces perform a number of tasks, such as establish and close a connection with a database , send a request to a database , retrieve data from a database , and update data in a database. The commonly used classes and interfaces in the JDBC API are:
  • 17. DriverManager class : Loads the driver for the database. Driver (interface / Class) : Represents a database driver. All JDBC driver classes must implement the Driver interface. Connection interface : Enables you to establish a connection between a Java application and a database. Statement interface : Enables you to execute SQL statements ResultSet interface: Represents the information retrieved from a database. SQLException class: Provides information about the exceptions that occur while interacting with databases.
  • 18. To query a database and display the result using Java applications , you need to : 1. Load a driver 2. Connect to a database 3. Create and execute JDBC statements 4. Handle SQL exceptions
  • 19. Loading a Driver The first step to develop a JDBC application is to load and register the required driver using the driver manager . You can load and register a driver : 1. Programmatically : . Using the forName() method . Using the registerDriver () method 2. Manually: . By setting system property
  • 20. Using the forName () Method  The forName() method is available in the java.lang.Class class. The forName() method loads the JDBC driver and registers the driver with the driver manager. The syntax to load a JDBC driver to access a database is : Class.forName (“driver_name”); You can load the JDBC-ODBC Bridge driver using the following method call: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
  • 21. Using the registerDriver () method  You can create an instance of the Driver class to load a JDBC driver.  The syntax to declare an instance of the Driver class is : Driver d = new <driver-name>;  You can use the following statement to crate an instance of the Driver class: Driver d = new sun.jdbc.odbc.JdbcOdbcDriver ();  Once you have created the Driver object ,call the registerDriver () method to register it with the DriverManager.  You can register the JDBC-ODBC Bridge driver using the following method call to registerDriver () method: DriverManager.registerDriver (d) ;
  • 22. Setting System Property  Driver can also be loaded by setting system property for JDBC drivers.  You add the driver name to the jdbc.drivers system property to load a JDBC driver.  You use the –D command line option to set the system property on the command line.  The command to set the system property is : java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver Demo  In the preceding command , jdbc.drivers is the property name and sun.jdbc.odbc.JdbcOdbcDriver is the value that you need to set for the property.  After you load a driver , you need to establish the connection with a database.
  • 23. Connecting to a Database  You create an object of the Connection interface to establish a connection with a database.  You can create multiple Connection objects in a Java applications to access and retrieve data from multiple databases.  The DriverManager class provides the getConnection () to create a Connection object.  The getConnection () is an overloaded method that has the following 3 forms: 1. Connection getConnection(String url) : 2. Connection getConnection (String url , String uname ,String pass) 3. Connection getConnection(String url , Properties properties)
  • 24. String url = “jdbc:odbc:MyDataSource” ; Connection con = DriverManager.getConnection(url); The syntax for the JDBC url that is passed as a parameter to the getConnection() method is : <protocol>:<subprotocol>:<subname> 1. Protocol name : Indicates the name of the protocol that is used to access a database. In JDBC, the name of the access protocol is always jdbc . 2. Sub-protocol name : Indicates the mechanism to retrieve data from a database. For example, if you use the JDBC-ODBC Bridge to access a database, then the name of the sub protocol is odbc . 3. Subname : Indiacates the Data Source Name (DSN) that contains database information, such as the name of a database , location of the database server , user name , and password to access a database server.
  • 25. String url = “jdbc:odbc:MyDataSource”; Connection con= DriverManager.getConnection(url,”uname”,”pass”); String url = “jdbc:odbc:MyDataSource”; Properties p = new Properties(); p.setProperty(“user” , “Newuser”); p.setProperty(“password”,”NewPassword”); Connection con = DriverManager.getConnection(url , p); After you create a connection ,you need to write JDBC statements that are to be executed.
  • 26. Creating and Executing JDBC Statements  You need to create a Statement object to send requests to and retrieve results from a database.  The Connection object provides the createStatement () method to create a Statement object. Statement stmt = con.createStatement();
  • 27. The Statement interface contains the following methods to send static statements to a database: 1. ResultSet executeQuery (String str) : Executes an SQL statement and returns a single object of the type , ResultSet. The executeQuery () should be used when you need to retrieve data from a database table using the SELECT statement. Statement stmt = con.createStatement (); ResultSet rs = stmt.executeQuery(<SQL statement >); 2. int executeUpdate(String str) : Executes the SQL statements and returns the number of data rows that are affected after processing the SQL statement. When you need to modify data in a database table using the DML statements , INSERT, DELETE, and UPDATE you can use the executeUpdate() . Statement stmt = con.createStatement (); ResultSet rs = stmt.executeUpdate(<SQL statement >);
  • 28. 3. boolean execute (String str ) : Executes an SQL statement and returns a boolean value. You can use this method when the type of SQL statement passed as parameter is not known or when the statement being executed returns a result set or an update count. The execute () method returns true if the of the SQL statement is an object of ResultSet and false if it is an update count. Statement stmt = con.createStatement(); stmt.execute(<SQL statement>); You can use the DML statements , INSERT , UPDATE and DELETE , in Java applications to modify the data stored in the databasetables. You can also use the DDL statements, CREATE, ALTER and DROP in java applications to define or change the structure of database objects.
  • 29. Querying a Table String str = “SELECT * from authors” ; Statement stmt = con.createStatement (); ResultSet rs = stmt.executeQuery(str); String str = “SELECT * from authors WHERE city = ‘Pune’ ” ; Statement stmt = con.createStatement (); ResultSet rs = stmt.executeQuery(str);
  • 30. Inserting Rows in a Table String str = “INSERT INTO authors (au_id, au_lname) VALUES (‘998’,’ABC’)” ; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); String str = “DELETE FROM authors WHERE lname=‘ABC’ ” ; String str = “CREATE TABLE MyProduct” + “ (p_id INTEGER, ” + ”p_name VARCHAR(25), ” + “rate FLOAT ,” + “unit_msr CHAR (6) )” ;
  • 31. String str = “ALTER TABLE MyProduct” + “ADD quantity INTEGER” ; String str = “DROP TABLE MyProduct” ;
  • 32. Handling SQL Exceptions  The java.sql package provides the SQLException class , which is derived from the java.lang.Exception class.  The SQLException is thrown by various methods in the JDBC API and enables you to determine the reason of the errors that occur while connecting a Java application to a database.  You can catch the SQLException in a Java application using the try and catch exception handling block.  The methods in the SQLException class are : 1. int getErrorCode () : Returns the error code associated with the error occurred. 2. String getSQLState() : X/Open error code. 3. SQLException getNextException () : Returns the next exceptions in the chain of exceptions.
  • 33. Try { String str = “DELETE FROM authors WHERE au_id = ‘123’ ” ; Statement stmt = con.createStatement(); int count = stmt.executeUpdate (str) ; } catch (SQLException sqlexception) { System.out.println (“Display Error Code”) ; System.out.println( “SQL Exception” + sqlexception.getErrorCode ()) ; }
  • 34. Result Sets  When you execute a query to retrieve data from a table using a java application , the output of the query is stored in a ResultSet object in a tabular format.  A ResultSet objects maintains a cursor that enables you to move through the rows stored in a ResultSet object.  By Default , the ResultSet object maintains a cursor that moves in the forward direction only.  As a result , it moves from the first row to the last row in the ResultSet.  You cannot update the default ResultSet object.  The cursor in the ResultSet object initially points before the first row
  • 35. Type of Results Sets  Read only : Allows you to only read the rows in a ResultSet object.  Forward only : Allows you to move the result set cursor from first row to last row in forward direction only.  Scrollable : Allows you to move the result set cursor forward or backward through the result set.  Updatable : Allows you to update the result set rows retrieved from a database table. You can specify the type of a ResultSet object using the createStatement () of the Connection interface. The createStatement() accepts ResultSet fields as parameters to create different types of the ResultSet objects.
  • 36. ResultSet fields  TYPE_SCROLL_SENSITIVE : Specifies that the cursor of the ResultSet object is scrollable and it reflects the changes in the data made by the other users.  TYPE_SCROLL_INSENSITIVE : Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by the other users.  TYPE_FORWARD_ONLY : Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row.  CONCUR_READ_ONLY : Specifies the concurrency mode that does not allow you to update the ResultSet object.  CONCUR_UPDATABLE : specifies the concurrency mode that allows you to update the ResultSet object.  HOLD_CURSORS_OVER_COMMIT : Specifies that a ResultSet object should not be closed after data is committed to the database.  CLOSE_CURSORS_AT_COMMIT : Specifies that a Result Set object should be closed after data is committed to the database.
  • 37. The createStatement() is an overloaded method that has 3 prototypes. 1. Statement createStatement () : Does not accept any parameter. This method creates a default ResultSet object that only allows forward scrolling. 2. Statement createStatement (int , int) : The first parameter indicates the ResultSet type that determines whether or not , a result set cursor can move backward. The second parameter indicates the concurrency mode for the result set that determines whether the data in result set can be updates . This method creates a ResultSet object with the given type and concurrency. 3. Statement createStatement (int , int , int ) : In addition to he ResultSet types and the concurrency mode , this method accepts a third parameter. This parameter indicates whether or not, the result set is closed after committing data to the database. This method creates a ResultSet object with the given type , concurrency and state.
  • 38. Methods of ResultSet  boolean first () : Shifts the control of a result set cursor to the first row of the result set.  boolean isFirst() : Determines whether the result set cursors points to the first row of the result set.  boolean beforeFirst() : Shifts the control of a result set cursor before the first row of the result set.  boolean isBeforeFirst () : Determines whether the result set cursor points before the first row of the result set.  boolean last() : Shifts the control of a result set cursor to the last row of the result set.  boolean isLast () : Determines whether the result set cursor points to the last row of the result set.
  • 39.  boolean afterLast() : Shifts the control of a result set cursor after the last row of the result set.  boolean isAfterLast () : Determines whether the result set cursor points after the last row of the result set.  boolean previous () : Shifts the control of a result set cursoe to the previous row of the result set.  boolean absolute (int i) : Shifts the control of a result set cursor to the row number that you specify as a paramter.  boolean relative (int i) : Shifts the control of a result set cursor , forward or backward , relative to he row number that you specify as a paramter .This method accepts either a positive or a negative values as a paramter
  • 40. Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(“SELECT * FROM authors”) if (rs.isBeforeFirst()== true) System.out.println(“Result set cursor id before first row in result set”); if (rs.first() == true) System.out.println(rs.getString(1) + “,” + rs.getString(2)+”,”+rs.getString(3)); System.out.println(“using absolute() method”); rs.absolute(4); int rowcount = rs.getRow() ; System.out.println(“rowNum should be 4 ” + rowcount);
  • 41.  JDBC allows you to create an updatable result set that enables you to modify the rows in the result set.  The following methods used with updatable result set: 1 . void updateRow () : Updates a row of the current ResultSet object and the underlying database tables. 2. void insertRow () : Inserts a row in the current ResultSet object and underlying database table. 3. void deleteRow () : Deletes a row from the current ResultSet object and underlying database table. 4. void updateString () : Updates the specified column with the given string value. 5. void updateInt() : Updates the specified column with the given int value.
  • 42. Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery (“SELECT au_id , city , state FROM authors WHERE au_id = ‘123’ ”) ; rs.next () ; rs.updateString(“state” , “MAHARASHTRA”) ; rs.updateString(“city” , “Pune”); rs.updateRow() ;
  • 43. Assignment  Create an application to retrieve information (author id , name , address , city and state ) about the authors who are living in the city where the city name begins with the letter “ P ” . Don’t use servlet and JSP for this ,USE Simple java program .
  • 44. PreparedStatement interface  The PreparedStatement objects accepts the runtime parameters.  The PreparedStatement interface is derived from the Statement interface and is available in the java.sql package.  The PreparedStatement objects are compiled and prepared only once by JDBC.  The future invocation of the PreparedStatement object does not recompile the SQL statements.  This helps in reducing the load on the database server and thus improving the performance of the application .
  • 45.  The PreparedStatement interface inherits the following methods to execute SQL statement s from the Statement interface: 1. ResultSet executeQuery () : Executes a SELECT statement and returns the result in a ResultSet object. 2. int executeUpdate(): Executes an SQL statement, INSERT , UPDATE , or DELETE and returns the count of the rows affected. 3. boolean execute () : Executes an SQL statement and returns a boolean value.
  • 46. stat = con.prepareStatement(“SELECT * FROM authors WHERE au_id = ? ”) ; The SQL statement can contain ‘ ? ‘ symbol as placeholder that can be replaced by input parameters at runtime. Before executing the SQL statements specified in the PreparedStatement object , you must set the value of each ‘ ? ‘ parameter. This is done by calling an appropriate setXXX () method , where XXX is the data type of the parameter. stat.setString (1, “123”); ResultSet rs = stat.executeQuery ();
  • 47.  The PreparedStatement interface provides various methods to set the value of the placeholders for the specific data types. 1. void setByte (int index , byte val) : Sets the java byte type value for the parameter corresponding to index passed as a parameter. 2. void setBytes (int index , byte[] val) : Sets the Java byte type array for the parameter corresponding to index passed as a parameter. 3. void setBoolean (int index , boolean val) : Sets the Java boolean type value for the parameter corresponding to index passed as a parameter. 4. void setDouble (int index, double val) : Sets the Java double type value value for the parameter corresponding to the index passed as a parameter.
  • 48. 5. void setInt (int index , int val) : Sets the Java int type value for the parameter corresponding to index passed as a parameter. 6. void setLong(int index , long val) : Sets the Java long type value for the parameter corresponding to index passed as a parameter. 7. void setFloat (int index , float val) : Sets the Java float type value for the parameter corresponding to index passed as a parameter. 8. void setShort (int index , short val) : Sets the Java short type value for the parameter corresponding to index passed as a parameter. 9. void setString(int index , String val) : Sets the Java String type value for the parameter corresponding to index passed as a parameter.
  • 49. Retrieving Rows String str = “SELECT * FROM titles WHERE au_id = ? ” ; PreparedStatement ps = con.prepareStatement(str) ; ps.setString(1 , “101”); ResultSet rs = ps.executeQuery ();
  • 50. Inserting Rows String str = “ INSERT INTO authors (au_id , au_fname , au_lname) VALUES (? , ? , ? ) ” ; PreparedStatement ps = con.prepareStatement(str); ps.setString (1, “101”); ps.setString (2, “ABC”); ps.setString (3 , “XYZ”); int rt = ps.executeUpdate() ;
  • 51. Updating & Deleting Row String str = “ UPDATE authors SET state = ? WHERE city = ? “ ; PreparedStatement ps = con.prepareStatement(str); ps.setString (1, “MH”); ps.setString (2, “Pune”); int rt = ps.executeUpdate() ; String str = “ DELETE FROM authors WHERE au_fname = ? “ ; PreparedStatement ps = con.prepareStatement(str); ps.setString (1, “PPPP”); int rt = ps.executeUpdate() ;
  • 52. Transactions  A transaction is a set of one or more SQL statements that are executed as a single unit.  A transaction is complete only when all the SQL statement in a trasaction execute successfully.  If any one of the SQL statements in the transaction fails , the entire transaction is rolled back thereby maintaining consistency of the data in the database.  JDBC API provides support for transaction management.  E.g. : transfer of money from a bank account.
  • 53. The database transactions can be committed in two ways in the JDBC applications. Implicit : The Connection object uses the auto-commit mode to execute the SQL statements implicitly. The auto-commit mode specifies that each SQL statement in a transaction is committed automatically as soon as the execution of SQL statement completes. By default all the transaction statement in a JDBC application are auto- committed. Explicit : For explicitly committing transaction statement in a JDBC application, you have to use the setAutoCommit () method . This method accepts either of the two values , true or false , to set or reset the auto-commit mode for a database. The auto-commit mode is set to false to commit a transaction explicitly . You can set the auto-commit mode to false using the following method call : con.setAutoCommit (false) ;
  • 54.  When you set the auto-commit mode to false ,the operations performed by the SQL statement are not reflected permanently in a database.  You need to explicitly call the commit () method of the Connection interface to reflect the changes made by the transactions in a database.  All the SQL statement that appear between two commit() methods are treated as a single transaction and are executed as a single unit.  The rollback () method is used to undo the changes made in the database after the last commit operations.  You need to explicitly invoke the rollback () method to revert a database in the last committed state.  When a rollback () method is invoked , all the pending transactions of a database are cancelled and the database reverts the state in which it was committed previously.  You can call the rollback () method using the following method call : con.rollback () ;
  • 55. Batch Updates  A batch is a group of update statements that are sent to a database to be executed as a single unit.  You send the batch to a database in a single request using the same Connection object.  This reduces network calls between the application and the database .  For this reason , processing the multiple SQL statements in a batch is a more efficient way as compared to the processing of a single SQL statement.  A JDBC transaction can comprise of multiple batches.
  • 56. Implementing Batch Updates in JDBC  The SQL statements that are part of a batch are called the batchable statements.  The Statement or PreparedStatement interface provides following methods to create and executes a batch of SQL statements : 1. void addBatch () : Adds an SQL statement to a batch . 2. void executeBatch () : Sends a batch of SQL statements to a database for processing and returns the total number of the rows updated. 3. void clearBatch () : Removes the SQL statements from the batch.
  • 57.  You can create Statement object to perform batch updates.  When a Statement object is created an empty array is associated with the object.  You can add multiple SQL statements to the empty array to execute them as a batch.  You also need to disable the auto-commit mode using setAutoCommit (false) while working with batch updates in JDBC.  This enables you to rollback the entire transaction performed using a batch update if any SQL statement in the batch fails.
  • 58. con.setAutoCommit (false) ; Statement stmt = con.createStatement () ; stmt.addBatch(“INSERT INTO product (p-id , p-desc) VALUES (1001,’PRINTER’) ”) ; stmt.addBatch(“INSERT INTO product (p_id , p_desc) VALUES (1002,’SCANNER’) ”); The SQL statement in a batch are processed in the order in which the statements appear in a batch. int [] updcount = stat.executeBatch () ;
  • 59. Exception-Handling in Batch Updates  The batch update operations can throw two types of exceptions , SQLException and BatchUpdateException.  The JDBC API methods, addBatch () or executeBatch () throw the SQLException when problem occurs while accessing a database.  The SQLException exception is thrown when you try to execute a SELECT statement using the executeBatch () method.  The BatchUpdateException class is derived from SQLException class.  The BatchUpdateException exception is thrown when the SQL statement in the batch cannot be executed due to : 1. Presence of illegal arguments in the SQL statement. 2. Absence of the database table.
  • 60.  The BatchUpdateException uses an array of the update count to identify the SQL statement that throws the exception.  The update count for all the SQL statement that are executed successfully is stored in the array in the same order in which the SQL statement appear in the batch.  You can traverse the array of update count to determine the SQL statement that is not executed successfully in a batch.  The null value in an array of update count indicates that the SQL statement in the batch failed to execute.
  • 61. import java.sql.*; public class BatchUpdate { public static void main (String arg []) { try { / * Batch Update Code comes here */ } catch (BatchUpdateException bexp) { System.err.println (“SQL Exception :” + bexp.getMessage ()) ; System.err.println(“Update Counts”) ; int [] count = bexp.getUPdateCounts(); for (int I = 0 ; i<=count.length ; i++ ) System.err.println(count[i]) ; } }
  • 62. Assignment  Creating an Application to insert Rows in a Table Using Batch Updates
  • 63. Stored Procedures  The java.sql package provides the CallableStatement interface that contains various methods to enable you to call database stored procedures.  The CallableStatement interface is derived form the PreparedStatement interface.
  • 64. Creating Stored Procedures  You can use the executeUpdate () to execute the CREATE PROCEDURE SQL statement.  Stored procedures can be of two types , parameterized and non- parameterized.  Non – parameterized stored procedure in a JDBC application: String str = “ CREATE PROCEDURE authors_info” + “AS” + “SELECT au_id , au_lname , au_fname” + ”FROM authors” + “WHERE city = ‘Pune’ ” + ”ORDER BY au_fname” ; Statement stmt = con.createStatement () ; int rt = stmt.executeUpdate (str);
  • 65.  The Connection object con is used to send the CREATE PROCEDURE SQL statement to a database.  When you execute the code , the authors_info stored procedure is created and stored in the database.
  • 66.  You can use the following code snippet to create a parameterized stored procedure. String str = “ CREATE PROCEDURE authors_info_prmtz @auth_id varchar(15) , @auth_fname varchar(20) output , @auth_lname varchar(20) output , @auth_city varchar(20) output , @auth_state varchar(20) output ” + “AS” + “SELECT @auth_fname = au_fname , @auth_lname = au_lname , @auth_city = city , @auth_state = state ” + “ FROM authors ” + “ WHERE au_id = @auth_id ” ; Statement stmt = con.createStatement () ; int rt = stmt.executeUpdate (str);
  • 67.  In the preceding code snippet , the authors_info_prmtz stored procedure is created that accepts author id as parameter and retrieve the corresponding author information form the database.  The retrieved information is stored in the OUT parameter.  The SQL Server 2000 uses output keyword to represent OUT parameters.  A stored procedure can accepts one or multiple parameters.  A parameter of a stored procedure can take any of these forms : 1. IN : Refers to the argument that you pass to a stored procedure. 2. OUT : Refers to the return value of a stored procedure. 3. INOUT : Combines the functionality of the IN and OUT parameters. The INOUT parameter enables you to pass an argument to a stored procedure. The same parameter can also be used to store a return value of a stored procedure
  • 68. When you use the stored procedures to perform database operations, it reduces network traffic because instead of sending multiple SQL statements to a database , a single stored procedure is executed.
  • 69. Calling a Stored Procedure without Parameters  The Connection interface provides the prepareCall() method that is used to create the CallableStatement object .  This object is used to a call a stored procedure of a database .  The prepareCall () is an overloaded method that has the following 3 forms:
  • 70. 1. CallableStatement prepareCall (String str) : Creates a CallableStatement object to call a stored procedure. The prepareCall () accepts a string as a parameter that contains an SQL statement to call a stored procedure. You can also specify the placeholders to accept parameters in the SQL statement. 2. CallableStatement prepareCall(String str , int resSetType , int resSetConc): Creates a CallableStatement object that returns ResultSet object that has the specified result set type and concurrency mode. The method accepts following 3 parameter : String object :Contains the SQL statement to call a stored procedure. The SQL statement can contains one or more parameters. ResultSet types : Specifies any of the 3 result set types , TYPE_FORWARD_ONLY , TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE. ResultSet concurrency modes :Specifies either of these concurrency modes , CONCUR_READ_ONLY or CONCUR_UPDATABLE , for a result set
  • 71. 3. CallableStatement prepareCall (String str , int resSetType , int resSetConcur , int resSetHoldability) : Creates a CallableStatement object that returns a ResultSet object . This ResultSet object has the specified result type, concurrency mode, and constant to set the result set state.
  • 72. The syntax to call a stored procedure without parameter is : { call <procedure_name> } ; String str = “ {call authors_info}” ; CallableStatement cs = con.prepareCall (str) ; ResultSet rs = cs.executeQuery() ; while(rs.next()) { System.out.println(“Author ID :” + rs.getString(1) + “t”); System.out.println(“Author First Name :” + rs.getString(2) + “t”); System.out.println(“Author Last Name :” + rs.getString(3) + “t”); }
  • 73. Calling a Stored Procedure with Parameters  The SQL escape syntax is used to call a stored procedure with parameters.  There are two forms of the SQL escape syntax, one that contains result parameter and one that does not.  If the SQL escape syntax contains a result parameter, the result parameter is used to return a value from a stored procedure.  The result parameter is an OUT parameter. Other parameters of the SQL escape syntax can contain IN , OUT , or INOUT parameters.
  • 74.  The syntax to call a stored procedure with parameter is : { call <procedure_name> (?)} ;  You need to set the value of the IN parameters before the CallableStatement object executed , otherwise the SQLException is thrown while processing the stored procedure. <CallableStatement_object>.setInt(<value>)
  • 75.  If the stored procedure contains OUT and INOUT parameters, these parameters should be registered with corresponding JDBC types before a call to a stored procedures is precessed.  The JDBC types determine the Java data types that are used in the get methods while retrieving the values of the OUT and INOUT parameters. cs.registerOutParameter (1 . Java.sql.Types.STRING) ; Accepts the position of the placeholder and a constant in the java.sql.Types class as parameters. cs.registerOutParameter (1, java.sql.Types.DECIMAL , 3) ; What for 3rd Parameter used for ?
  • 76. import java.sql.*; public class CallProc { public static void main(String arg []) { String id , fname , lname , address , city ; try { String str = “ { call authors_info ( ? , ? , ? , ? , ? ) } ” ; Class.forname (“sun.jdbc.odbc.JdbcOdbcDriver”); Connection con = DriverManager.getConnection(“jdbc:odbc:DSN”) ; CallableStatement cs = con.prepareCall (str) ; // pass IN parameter cs.setString (1 , “123-456” ) ;
  • 77. //Register OUT paramter cs.registerOutParameter(2 , Types.VARCHAR); cs.registerOutParameter(3 , Types.VARCHAR); cs.registerOutParameter(4 , Types.VARCHAR); cs.registerOutParameter(5 , Types.VARCHAR); // process the Stored procedure cs.execute () ; fname = cs.getString(2) ; lname = cs.getString(3) ; address = cs.getString(4) ; city = cs.getString(5) ; ---- ----- ---- }
  • 78. Using METADATA in JDBC  Metadata is the information about data , such as structure and properties of a table.  Employee table that has the name , address , salary , designation and department columns.  The metadata of the employee table includes information , such as names of the columns , data type of each column and constraints to enter data values in the table columns.  The JDBC API provides the following 2 metadata interfaces to retrieve the information about the database and result set : 1 . DatabaseMetaData interface 2 . ResultSetMetaData interface
  • 79. DatabaseMetaData Interface  The DatabaseMetaData interface provides the methods that enable you to determine the properties of a database or RDBMS.  These properties include names of database tables , database version , SQL keywords , etc…. .  You can create an object of DatabaseMetaData using the getMetaData () of the Connection interface. DatabaseMetaData dm = con.getMetaData () ;  The following lists the commonly used methods of the DatabaseMetaData interface :
  • 80.  ResultSet getColumns (String catalog , String schema, String tablename String col_name) -> Retrieves the information about a column of a database table that is available in the specified database catalog.  Connection getConnection () -> Retrieves the database connection that creates the DatabaseMetaData object.  String getDriverName () -> Retrieves the name of the JDBC driver for the DatabaseMetaData object .  String getDriverVersion () -> Retrieves the version of the JDBC driver.
  • 81.  ResultSet getPrimaryKeys (String catalog , String schema , String table) -> Retrieves the information about the primary keys of the database tables.  String getURL () -> Retrieves the URL of the database  boolean isReadOnly () -> Returns a boolean value that indicates whether the database is a read only database.  boolean supportsSavePoints () -> Returns a boolean value that indicates whether the database supports savepoints.
  • 82. Using ResultMetaData Interface  The ResultSetMetaData interface contains various methods that enable you to retrieve information about the data in a result set , such as number of columns , names of columns and data types of the columns.  The ResultSet interface provides the getMetaData () method to create an object of the ResultSetMetaData interface . ResultSetMetaData rm = rs.getMetaData() ;  The following lists the commonly used methods of the ResultSetMetaData interface :
  • 83.  int getColumnCount () : Returns an integer indicating the total number of columns in a ResultSet object .  String getColumnLabel (int col_index) : Retrieves the title of the table column corresponding to the index passed as a parameter to this method.  String getColumnName (int col_index) : Retrieves the name of the table column corresponding to the index passed as a parameter to this method.  int getColumnType (int col_index) : Retrieves the SQL data type of the table column corresponding to the index passed as a parameter.  String getTableName(int col_index) : Retrieves the name of the database table that contains the column corresponding to the index passed as a parameter.
  • 84.  boolean isAutoIncrement (int col_index) : Returns a boolean value that indicates whether the table column corresponding to the index passed as a parameter increments automatically.  boolean isCaseSensitive (int col_index) : Returns a boolean value that indicates whether the table column corresponding to the index passed as a parameter is case sensitive.  boolean isReadOnly (int col_index) : Returns a boolean value that indicates whether the column in a ResultSet corresponding to the index passed as a parameter is read only.  boolean isWritable (int col_index) : Returns a boolean value that indicates whether ResultSet column corresponding to the index passed as a parameter is updatable.
  • 85. Assignment The Manager of New Publishers publishing company , sometimes require the information about the tables of the database used by the company. He is not familiar with the SQL statements , therefore , he has asked you to create an application to determine the total number of columns and the data types of the columns of a given table . The table name has to be specified at the runtime.
  • 86. The java.sql package Some commonly used interfaces of the java.sql package are : 1. Statement 2. PreparedStatement 3. CallableStatement 4. Connection 5. ResultSet 6. DatabaseMetaData 7. ResultSetMetaData
  • 87. The javax.sql Package The commonly used interface of the javax,sql package is DataSource
  • 88. Assignment 1. Create a Java application to insert data in the product table using the Statement object. 2. Create a Java application that uses scrollable result set to display information retrieved from the customer table. 3. Create a Java application to perform batch updates. The application should insert information about a new customer in the customer table.