Part 2
Part 2
2
3
JDBC stands for Java Database Connectivity,
which is a standard Java API for database
independent connectivity between the Java
programming language and a wide range of
databases.
The JDBC library includes APIs for each of the
tasks mentioned below that are commonly
associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
4
Fundamentally, JDBC is a specification that
provides a complete set of interfaces that allows
for portable access to an underlying database.
Java can be used to write different types of
executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use
a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC,
allowing Java programs to contain database
independent code.
5
Java Database Connectivity (JDBC) is an
application program interface (API) specification
for connecting programs written in Java to the
data in popular databases.
The application program interface lets you
encode access request statements in Structured
Query Language (SQL) then passed to program
that manages database.
It returns results through similar interface.
JDBC is very similar to SQL Access Group's Open
Database Connectivity (ODBC) and, with a small
"bridge" program, you can use the JDBC interface
to access databases through the ODBC interface.
6
For example, you could write a program
designed to access many popular database
products on a number of operating system
platforms.
For example, Microsoft Access database, your
program with JDBC statements would be able to
access Microsoft Access database.
JDBC specifies a set of object-oriented classes
for the programmer to use in building SQL
requests. An additional set of classes describes
the JDBC driver API.
10
SQL JDBC/JAVA SetXXX GetXXX
Varchar Java.lang.string setString getString
11
For processing queries we need to follow some
steps
Load driver
Open and return connection
Create and return statement
Execute statement and return statement if
required
Traverse result set
Return records
12
13
The sql exception class extends the general
java.lang.Exception class. it is an exception that
provides information on database access error or
other errors.
Exception handling allows you to handle exceptional
conditions such as program-defined errors in
controlled fashion. When an exception condition
occurs, an exception is thrown.
The term thrown means that current program
execution is stop, and the control is redirected to
the nearest applicable catch clause. If no applicable
catch clause exists, then the program's execution
ends.
JDBC Exception handling is very similar to the Java
Exception handling but for JDBC, the most common
exception you'll deal with is java.sql.SQLException.
14
15
Before talking about JDBC Driver types let us
discuss about JDBC driver. Database vendors
provides a driver along with the database.
These database drivers are used to communicate
with java programs. The JDBC driver are provided
by database vendors to enable JDBC API to
communicate with database.
The java program invoke the methods of JDBC
API.
JDBC drivers are divided into four categories.
Each category defines JDBC driver
implementation with increasingly higher levels of
platform independence, performance.
16
The four categories of JDBC driver are :
Type 1 : JDBC-ODBC Bridge
Type 2 : Native-API / Partly-java driver
Type 3 : Net-protocol/ all-java driver
Type 4 : Native-protocol/all-java driver
Type 1 : JDBC-ODBC Bridge:
The JDBC-ODBC bridge driver convert all JDBC call
into ODBC call & sends them to ODBC driver. The
ODBC driver then forward the call to database
server.
Fig. shows communication between java
application & database using JDBC-ODBC Bridge.
Instead they provide Open Database Connectivity
(ODBC ) driver. One can access such database by
using ODBC-JDBC Bridge.
17
18
Advantage:
easy to use.
can be easily connected to any database.
Disadvantages :
Since the bridge driver is not written fully in java.
Type 1 driver are not portable.
Performance is slowest in comparison to all driver
because the JDBC calls are first converted to ODBC
calls. ODBC calls are then converted to native
database calls. The same steps are performed in
reverse order when the result of the query is
obtained.
The client system requires the ODBC Installation to
use driver.
Not good for the Web application or for large scale
database based application.
19
Type 2 : Native-API / Partly-java driver:
The JDBC type-2 driver, or the native-API/partly-
java driver, communicates directly with the
database server. Therefore, the vendor database
library needs to be loaded on each client
computer.
The type 2 driver converts JDBC calls into
database-specific calls for database. Example :
Oracle will have oracle native API
Advantage
They are typically offer better performance than
the JDBC-ODBC Bridge.
Because as the layers of communication(tiers) are
less than type 1 driver & also it uses native API
which is database specific.
20
21
Type 3 : Net-protocol /all-java driver Or Network
Protocol driver
The JDBC type 3 driver, or the net-protocol/all-
java driver, follows a three-tiered approach.
JDBC database request are passed to a middle-
tier server. The middle-tier server then translates
the request & passes to the database-specific
native-connectivity interface & forwards the
request to the database server.
Type 3 driver are used to connect a client
application or applet to database over TCP/IP
connection.
22
23
Advantages :
This driver is server-based, so there is no need for any
vendor database library to be present on client machines.
This driver is fully written in java & hence portable, so it is
suitable for the web application.
Disadvantage:
Disadvantage:
27
(1) getConnection():
Connection interface defines connection to the
different database.
An instance of connection interface obtained
from getConnection() method of DriverManager
class.
It is also able to get the information about table
structure of database, its supported SQL
grammar, its stored procedures, the capabilities
of this connection & so on.
This information is obtained with the
getMetaData() method.
It is used to create a statement object for
sending SQL statement to the database
28
29
If the same SQL statement is executed many
times, it is difficult to use Statement interface
instead of it we can use Prepared Statement
interface & its preparStatement() method.
(2) prepareStatement():-
It is used to create a prepared statement object
for sending SQL statement to the database A
SQL statement with or without IN parameters can
be pre-compiled and stored in a Prepared
Statement object. This object can then be used
to efficiently execute this statement multiple
times.
Example:
PreparedStamanet pst;
pst=con.prepareStatement(sql);
30
(3) prepareCall():-
It is used to create object of Callable Statement
for calling stored procedure of database, the
Callable Statement object provides methods for
setting up it’s IN & OUT paramenters & methods
for executing the call to stored procedure.
Example:
CallableStatement cst=con.prepareCall(“call
insertdata(? ,?) }”);
cst.setString(1,sid);
cst.setString(2,sname);
cst.executeUpdate();
31
(4) close():
(5) commit():
it is used to save all the state of the database
which are changed by transaction. It can be
written as follow
con.commit();
32
(6) getMetaData():-
It is used to get metadata (data about data)
related to current connection with the database.
It provides the information related to dataset like
table driver name, driver type its version & so on.
It uses DatabaseMetaData interface to get the
information database driver.
For example
Connection con;
con =DriverManager.getConnection (url, “ “, “ “);
DatabaseMetadata ds=con.getMetaData();
33
(7) setAutoCommit():
It is used to do auto commit with all the SQL
statements. If we set the auto commit with the
connection all the SQL statements executed &
committed with together as individual
transaction.
It has one parameter of Boolean type with it. If we
pass true as a parameter it enables the auto
commit & if we pass false it disables the auto
commit.
For example :
con.setAutoCommit(true);
34
(8) getAutoCommit():
38
execute():
It is used to execute the SQL statement which
return the multiple results.
It return the Boolean indicating value if it return
true then it defines that the next result is Result
Set object & if it return false then it define no. of
record updated or no more result is there. It
passes any SQL statement as parameter.
39
PreparedStatement Interface is derived from
statement interface.
Disadvantage of Statement object is it executes
simple SQL statement with no parameters & the
SQL statement is not precompiled.
But PreparedStatement object uses a template to
create SQL request & use PreparedStatement
precompiled SQL statements with one or more
parameters.
So, sometimes it is more convenient to use
PreparedStatement object for sending SQL
statement to database.
40
If you want to execute SQL statement many
times, PreparedStatement object reduces
execution time in comparison to Statement
object.
Using this advantage PreparedStatement object
contains not only SQL statement but precompiled
SQL statement.
Though PreparedStatement objects can be used
for SQL statement with no parameters
SQL statements take parameters for same
statement & supply different values each time
you execute it.
41
Creating Object using prepared statement
interface:
String sql=”insert into
tablename(fieldname1,fieldname2) values(?,?)”;
PreparedStatement
pstmt=con.PreparedStatement(sql);
setXXX methods :
1) setInt(int parameterIndex, int x)
2) setChar(int parameterIndex,char x)
3) setString(int parameterIndex,String x)
4) setFloat(int parameterIndex,float x)
5) setDouble(int parameterIndex,double x)
6) setLong(int parameterIndex,long x)
42
1) executeQuery()
This method is used to fetch records from
database by using select query. It can only return
single Result Set object at a time.
It passes parameter with it which is SQL
statement which selects records from database.
Example :
ResultSet rs;
String sql=”select * from tablename where
fieldname=?”;
setString(1,”C01”);
PreparedStatement
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
43
2) executeUpdate()
This methods is used to perform insert, update &
delete operation on records of database.
It return integer value which indicates number of
records updated in the database. It passes SQL
statement as parameter which updates records of
database.
Example :
Statement st=con.createStatement();
44
3) execute()
It is used to execute the SQL statement which
returns multiple results.
It returns the Boolean indicating value if it return
true it defines that the next result is ResultSet
object & if it return false then it defines number
of records updated or no more result is there. It
passes any SQL statement as parameter.
45
Q22) Callable Statement:
A CallableStatement object provides a way to call
stored procedures in a standard way for all
DBMS.
This call is written in an escape syntax that may
take one of two forms : one form with a result
parameter & the other without one.
A result parameter, a kind of OUT parameter, is
return value for stored procedure.
Both for may have variable number of parameters
used for IN parameter, OUT parameters, or both
INOUT parameters.
A question mark serves as a placeholder for a
parameter.
46
Syntax for stored procedure with IN parameters :
{call procedure_name [(?,?,..)]}
Syntax for stored procedure with IN & OUT
parameters :
{?=call procedure_name [(?,?,..)]}
Syntax for stored procedure with no parameters :
{call procedure_name}
Before creating an object of CallableStatement we
would already know that DBMS being used
supports stored procedures & what those
procedures are ?
suppose we don’t know about it & we want to
check than we can use different
DatabaseMetaData methods.
47
CallableStatement inherits Statement methods,
which deal with SQL statements in general, & it
also inherits PreparedStatement methods, which
deal with IN parameters.
CallableStatement objects are created with
Connection method prepareCall
48
Q23)
It is used to access the data of table from
database. ResultSet object stores data of table
by executing query.
It also maintains the cursor position for
navigation of the data. Cursor can move on first,
next, previous & last position from current row
position.
It also fetch data from table using getXXX
methods depends on column type(getXXX
method means getString(), getInt() etc
It can fetch data either passing column name or
index number with getXXX methods.
Index number always starts with one.
49
Fields of ResultSet interface :
All the following fields are static & return an
integer value.
1.CONCUR_READ_ONLY :It define that ResultSet
object can not be modified or updated.
2.TYPE_FORWARD_ONLY : It define that cursor
from the current row can move forward only.
3.TYPE_SCROLL_INSENSITIVE :It defines that
cursor can scroll but can not be modified or
update.
4. TYPE_SCROLL_SENSITIVE :It defines that cursor
can scroll & also can be modified or update.
50
Methods of ResultSet interface:
getXXX methods : following all the methods are
overloaded methods as we have discussed before
we can pass either column name or index
number as parameter with them.
getString() : It is used to fetch string type of
records from table. It return string object.
getInt() : it is used to fetch integer types of
records from table. It return integer value.
getBoolean() : it is used to fetch Boolean
indicating values from table. It return true or
false.
getDouble (): It is used to fetch decimal type of
values from table & return double value.
51
getFloat() : It is used to fetch decimal.
getDate : it return the date type of record from
the table.
getLong : it return long type of integer value
from the table.
With use of index number
Resultset rs=st.executeQuery(“select * from
emp”);
int id=rs.getInt(1);
String name=rs.getString(2);
String design=rs.getString(3);
loat sal=rs.getFloat(4);
52
Withuse of column name
Resultset rs=st.executeQuery(“select * from
emp”);
int id=rs.getInt(“empid”);
String name=rs.getString(“empname”);
String design=rs.getString(“empdesig”);
Float sal=rs.getFloat(empsalary”);
53
Q 24)
first() : it is used to move cursor position on the first record of
the table.
previous() : it is used to move cursor position on the previous
records of table from current position.
54
MetaData:
Meaning of metadata is data about data. There
are two types of metadata interface :
1.ResultSetMetaData interface
2.DatabaseMetaData Interface
55
This interface provides methods for obtaining
information about types & properties of column
in a Result-Set object.
ResultSet Metadata is used to store following
information of ResultSet object.
getCatalogName(int column) : gets the
designated column’s table’s catalog name.
getColumnClassName(int column) : return the
fully-qualified name of java class whose
instances are manufactured if the method
Resultset.getObject is called to retrieve a value
from the column.
56
getColumnCount() : Returns the number of columns
in this ResultSet object.
getColumnDisplaySize(int column) : Indicates
designated column’s normal maximum width in
characters.
getColumnName(int column) : get the designated
column’s name.
getColumnTypeName(int column): retrieves the
designated column’s database-specific type name.
getSchemaName(int column): Get designated
column’s table’s scheme.
getTableName(int column) :Gets designated column’s
table name.
isAutoIncrement(int column) : Indicates whether the
designated column is automatically numbered, thus
read-only.
isCaseSensitive(int column) : indicates whether a
column’s case matters.
57
This interface describes database as a whole.
Many methods of DataBaseMetadata interface
return lists of information in form of ResultSet
objects.
This interface provide many methods that
represent comprehensive information of
database. Database metadata is used to store
following information of Database Metadata
object
tables are available?
Should database know the table name?
Is database in read-only mode?
58
allProceduresAreCallable() : Retrieves whether
current user can call all procedure returned by
method getProcedures.
allTablesAreSelectable() : Retrieves whether
current user can use all tables returned by
SELECT statement.
getCatalogs() : Retrieve the catalog names
available in this database.
getConnection() : Retrieve the connection that
produced this metadata object.
getDatabaseProductName (): retrieve the name of
this database product.
getDatabaseProductVersion() : retrieve the
version number of this database product.
59
getDriverName () : retrieve the name of this JDBC
driver.
60