Professional Documents
Culture Documents
2
JDBC
Programmers connect to a database, query it or
update through a Java application.
Programs developed with Java & JDBC are
platform & vendor independent.
JDBC library is implemented in java.sql package.
3
JDBC
A driver is a program that converts the Java
method calls to the corresponding method calls
understandable by the database in use.
4
INTRODUCTION TO JDBC
JDBC is used for accessing databases
from Java applications
Information is transferred from relations
5
WHY ACCESS A DATABASE WITH JAVA?
6
PACKAGES TO IMPORT
7
JDBC ARCHITECTURE
Driver Oracle DB
Driver MS-Access
DB
10
ODBC- OPEN DATABASE CONNECTIVITY
A driver manager for managing drivers for SQL
based databases.
Developed by Microsoft to allow generic access to
disparate database systems on windows
platform.
J2SDK comes with JDBC-to-ODBC bridge
database driver to allow a java program to access
any ODBC data source.
11
JDBC VS ODBC
ODBC is a ‘C’ API
ODBC is hard to learn – because of low-level
native ODBC.
ODBC most suited for only Windows platform
No platform independence
12
JDBC(DRIVERS)
JDBC-ODBC Bridge (Type 1)
Native-API partly Java Driver(Type 2)
13
JDBC DRIVER TYPE 1
Java ODBC
JDBC API
Application Layer
JDBC
ODBC
ODBC Database
API
Driver
14
TYPE 1 DRIVER (JDBC-ODBC BRIDGE
DRIVER)
Disadvantages
ODBC required hence all problems regarding ODBC
follow.
Slow
15
JDBC DRIVER TYPE 2
Java Vendor
JDBC API
Application API
JDBC
Driver Database
16
TYPE 2 (NATIVE LIBRARY TO JAVA
IMPLEMENTATION)
17
JDBC DRIVER TYPE 3
Database
JDBC
Driver
18
TYPE 3 (PURE NETWORK PROTOCOL
JAVA DRIVER)
Uses DB independent protocol to communicate
DB-requests to a server component.
This then translates requests into a DB-specific
protocol.
Since client is independent of the actual DB,
deployment is simpler & more flexible.
19
JDBC DRIVER TYPE 4
Vendor-Specific
Protocol
Database
20
TYPE 4 DRIVER (PURE JAVA DRIVERS)
21
JDBC API
API layer has2 levels of interface.
Application layer: developer uses API to make calls to
DB via SQL & retrieve results.
Driver layer : handles all communication with a
specific Driver implementation.
22
ResultSet ResultSet ResultSet
PreparedStatement
Statement CallableStatement
Connection
Application
DriverManager
ODBC Driver
24
JDBC(INTERFACES)
Driver
Connection
Statement
PreparedStatement
CallableStatement
DatabaseMetadata
ResultSet
ResultSetMetadata
25
JDBC(CLASSES)
Date
DriverManager
DriverPropertyInfo
Time
TimeStamp
Types
26
To Query a database and display the result using java
application you need to follow four steps
1: Load the driver
27
Loading the driver:
1:Programatically
--Using forName() method
--Using registerdriver() method
2:Manually
--by setting System property
28
Using the forName() method
Class.forName(“<driver name>”);
Class.forName(“sun.jdbc.odbc.JdbcOdbcdriver”);
Using registerDriver() method
Driver d = new <drivername>;
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
DriverManager.registerDriver(d) ;
Using System property
Java –d jdbc.drivers=sun.jdbc.odbc.JdbdOdbcDriver App
29
CONNECTING TO THE DATABASE
Connection getConnection(String <url>);
String url=“jdbc:odbc:Mydatasource”;
<protocol>:<subprotocol>:<DataSourceName>
30
Overloaded getConnection() method
31
METHODS TO EXECUTE DIFFERENT
TYPES OF QUERIES
First create a statement object by invoking
createStatement() method on Connection object
Call the execute methods on this Statement
object as follows :
- Call execute (<sql stmt>) method for DDL
queries
- Call executeQuery(<sql stmt>) method for select
statement queries
- Call executeUpdate(<sql stmt>) method for
queries to update data
32
CREATING AND EXECUTING JDBC
STATEMENT
Statement stmt=con.createStatment();
ResultSet executeQuery(String str)
e.g.-ResultSet rs =stmt.executeQuery(<sql
stmt>);
int executeUpdate(String str)
e.g.-int count=stmt.executeupdate(<sql stmt>);
boolean execute(String)
e.g. boolean b = stmt.execute(< sql stmt >);
33
DRIVER INTERFACE
Connection connect(String URL, Properties info)
Checks to see if URL is valid.
Opens a TCP connection to host & port number
specified.
Returns an instance of Connection object.
34
DRIVER MANAGER CLASS
Connection getConnection(String URL)
void registerDriver(Driver driver)
void deregisterDriver()
35
VARIOUS DATABASE OPERATION THAT
YOU CAN PERFORM USING A JAVA
APPLICATION ARE
1:Querying a database
2:Inserting row in a table
36
CREATING A TABLE
String str=“CREATE TABLE MyProduct”+
“(p_id INTEGER)”+”p_name VARCHAR(24),”;
Statement stmt=con.createStatement();
stmt.execute(str);
37
QUERYING THE TABLE
You can retrieve the data from a table using the
SELECT statement.
38
INSERTING ROWS IN A TABLE
You can add rows in an existing table using the
INSERT statement
String str=“INSERT INTO authors
(au_id,au_lname,au_faname ) VALUES
(‘99’,’Sachin’,’Tendulkar’,’)”;
Statement stmt=con.createStatement();
int count=stmt.executeUpdate(str);
39
UPDATING ROWS IN A TABLE
String str=“UPDATE authors SET
l_name=“Bhosle”” WHERE au_id=99;
Statement stmt=con.createStatement();
ResultSet rs= stmt.executeUpdate(str);
40
DELETING ROWS FROM THE TABLE
String str=“DELETE from authors WHERE
au_id=99;
Statement stmt=con.createStatement();
ResultSet rs= stmt.executeUpdate(str);
41
HANDLING SQL EXCEPTION
int getErrorCode()
-Return the error code associated with the error
String getSQLState()
42
CONNECTION
Represents a session with the DB connection
provided by driver.
You use this object to execute queries & action
statements & commit or rollback transactions.
43
JDBC(CONNECTION)
close()
commit()
void setAutoCommit(boolean b)
rollback()
Statement createStatement()
44
JDBC(STATEMENT)
Statement
PreparedStatement
CallableStatement
Statement Methods
boolean execute(String sql)
45
STORED PROCEDURES
A stored procedures is a collection or batch of
statement and control of flow language that o
sstored under one name,and execute as one unit.
A stored procedures is a precompiled object
stored in the database.
This means that procedure is compiled
beforehand and is readily available for the
various application to execute.
46
BENEFITS OF STORED PROCEDURE
No time is spend on sending the query to the
server ,parsing and compiling at the server
again.
Improved Performance
Better consistency
47
THE CREATE PROCEDURE STATEMENT
CREATE PROCEDERE p_name
AS
BEGIN
sql_stmt1
sql_stmt2
END
48
EXAMPLE OF SP
CREATE PROCEDURE List
AS
BEGIN
SELECT c_name,v_Adress
FROM Agencies
END
49
CHECK THE EXISTENCE OF THE SP IN DB
Sp_helptext List
For Executing SP
EXECUTE List
Or
EXEC List
Or
List
50
CALLABLE STATEMENT
To call a stored procedure from within a J2ee
object, the callable statement object is used.
51
CALLABLE STATEMENT OBJECT
PARAMETER
52
CALLING THE STORED PROCEDURE
The Connection interface provide the
prepareCall() method that is used to create the
CallableStatement object.
53
SNIPPET EXAMPLE
String str =“{call authors_info}”;
callableStatement cstmt=con.prepareCall(str);
ResultSet rs=cstmt.executeQuery();
while(rs.next())
{
System.out.println(“Authorid::”+rs.getString(1));
System.out.println(“Authorid::”+rs.getString(2));
System.out.println(“Authorid::”+rs.getString(3));
}
54
RESULTSET INTERFACE
When you execute the query to retrieve the data
from a table using the java application ,the
output of the query is stored in the ResultSet
object in the tabuler format.
The ResultSet object maintains a cursor that
enables you to move through the rows stored in
the ResultSet object.
55
JAVA 2 RESULTSET
Statement stmt =
conn.createStatement(type, concurrency);
TYPE_FORWARD_ONLY
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
CONCUR_READ_ONLY
CONCUR_UPDATEABLE
HOLD_CURSORS_OVER –COMMIT
CLOSE_CURSORS_AT_COMMIT
56
JDBC(RESULTSET)
first()
last()
next()
previous()
beforeFirst()
afterLast()
absolute( int )
relative( int )
57
JDBC
Statement stmt =
con.createStatement(ResultSet.TYPE_SCRO
LL_ SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs.first();
rs.updateInt(2, 75858 );
rs.updateRow();
58
JDBC
ResultSet rs = stmt.executeQuery(“Select ….”);
rs.moveToInsertRow();
rs.updateString(1, “fkjafla” );
rs.updateInt(2, 7686);
rs.insertRow();
rs.last();
rs.deleteRow();
59
IMPLEMENTING BATCH UPDATES IN
JDBC
A batch is a group of update statement that are
sent to a database to be executed as a single unit.
You can send the batch to the database in a
single request using the same connection object.
This reduces network calls between the
application and the database.
A JDBC transaction can comprise of multiple
batches.
60
IMPLEMENTING BATCH UPDATES IN
JDBC
The statement or PreparedStatement interface
provide following methods to create and execute a
batch of sql statements.
void addBatch()
-Adds a sql statement to a batch .
int executeBatch()
-Sends a batch of sql statement to a database
for processing and return the number of rows
updated
void clearBatch()
-remove the sql statement batch from
database 61
CODE SNIPPET
Con.setAutoCommit(false)
Statement stmt=con.createStatement();
Stmt.addbatch(“INSERT INTO authors
(au_id,au_name ) VALUES (‘99’,’Sachin’)”);
Stmt.addbatch(“INSERT INTO authors
(au_id,au_name ) VALUES (‘100’,’RP’)”);
62
DATABASE METADATA
Metadata is the information about data such as
structure and properties of the table.
DatabaseMetaData dm=con.getMetaData()
63
DATABASE METADATA
ResultSet getColumns(String catalog,String
schema,String table_name,String
coloumn_name)
String getDriverName()
String DriverVersion()
64
RESULT SET METADATA INTERFACE
Object that can be used to find out about the
types and properties of the columns in a
ResultSet
Example
Number of columns
Column title
Column type
ResultSetMetaData rm= rs.getMetaData();
65
RESULTMETADATA INTERFACE
int getColumnCount()
String getColoumnName()
String getTablenName()
66
TRANSACTION
A transaction is a set of one or more SQL
statement that are executed as a single unit.
JDBC API provide support for transaction
management.
The database transaction can be commited in two
in a JDBC application
Implicit
Explicit
67
68