You are on page 1of 68

1

Made by: - Pankaj Malik


MBA-IT
OBJECTIVES OF THIS SESSION
 State what is Java Database Connectivity
 State different types of drivers supported by
JDBC
 Describe the steps to be followed for writing a
simple JDBC application
 Describe the use of Resultset interface

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

to objects and vice-versa


 Databases optimized for searching/indexing

 Objects optimized for engineering/flexibility

5
WHY ACCESS A DATABASE WITH JAVA?

 There are queries that can not be


computed in SQL:
 Given a table Bus(Source, Destination) find

all pairs of places that it is possible to travel


between (paths of any length)
 Java allows for a convenient user interface to the
database

6
PACKAGES TO IMPORT

 In order to connect to the Oracle


database from java, import the following
packages:
 java.sql.*; (usually enough)

 javax.sql.* (for advanced features, such as

scrollable result sets)

7
JDBC ARCHITECTURE

 The application creates a driver instance


and
registers it with the DriverManager.
 The DriverManager connects a driver to the
Database
 The DriverManager keeps track of
registered driver instances and their
connections to Databases.
 The Driver talks to a particular database
through the connection
8
9
JDBC

Driver Oracle DB

Java JDBC SQL server


Driver
Program API 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)

 Net-Protocol All-Java Driver (Type 3)

 Native Protocol All-Java Driver (Type 4)

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)

 Translates all JDBC API calls to ODBC API calls.


 Relies on an ODBC driver to communicate with the
database.

 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)

 Written partly in Java & partly in native code,


that communicates with the client API of a
database.
 Therefore, should install some platform-specific
code in addition to Java library.
 The driver uses native ‘C’ lang lib calls for
conversion.

17
JDBC DRIVER TYPE 3

Java JDBC Driver


JDBC API Native Driver
Client Server

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

Java JDBC Driver


JDBC API
Client (Pure Java)

Database

20
TYPE 4 DRIVER (PURE JAVA DRIVERS)

 JDBC calls are directly converted to network


protocol used by the DBMS server.

 Driver converts JDBC API calls to direct network


calls using vendor-specific networking protocols
by making direct socket connections with the DB.

 But driver usually comes only from DB-vendor.

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

Oracle Driver JDBC-ODBC Driver Sybase Driver

ODBC Driver

Oracle Access Sybase


Database Database Database 23
JDBC URL
 Needed by drivers to locate ,access and get other
valid information about the databases.
 jdbc:driver:database-name
 jdbc:Oracle:products
 jdbc:odbc:mydb; uid = aaa; pwd = secret
 jdbc:odbc:Sybase
 jdbc:odbc://whitehouse.gov.5000/cats;

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

 2: Connect to the database

 3: Create and execute the JDBC statement

 4: Handle the sql exception

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

1Connection getConnection(String url,String


user,String psw);
2Connection getConnection(String url,Properties
<prop>);
Properties p=new Properties();
p.setProperty(“user”,”Newuser”);
p.setProperty(“password”,”Newpassword”);
Connection con = driverManager.getConnection(url,p);

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.

 Boolean acceptsURL(String URL)

34
DRIVER MANAGER CLASS
 Connection getConnection(String URL)
 void registerDriver(Driver driver)

 void deregisterDriver()

 Eg : Connection conn = null;


 conn =
DriverManager.getConnection(“jdbc:odbc:mydsn”
);

35
VARIOUS DATABASE OPERATION THAT
YOU CAN PERFORM USING A JAVA
APPLICATION ARE

 1:Querying a database
 2:Inserting row in a table

 3:Deleting rows from a table

 4:Updating row in a table

 5:Altering and dropping 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.

 String str=“SELECT * FROM authors”;


Statement stmt=con.createStatement();
ResultSet rs= stmt.executeQuery(str);

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()

-Returns X/Open error code


 SQLException getNextException()

-Return the next exception in the chain of


exceptions

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()

 CallableStatement prepareCall(String sql)


 PreparedStatement prepareStatement(String
sql)

44
JDBC(STATEMENT)
 Statement
 PreparedStatement
 CallableStatement

 Statement Methods
 boolean execute(String sql)

 ResultSet executeQuery(String sql)

 int executeUpdate(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

 Reduction in Network Congestion

 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.

 By invoking the name of stored procedure the


stored procedure are executed.

51
CALLABLE STATEMENT OBJECT
PARAMETER

 INAny data is present in the IN parameter


that needs to be passed to stored procedure and
using the setxxx() method whose value is
assigned.
 OUTThe
The value returned by the stored
procedure is contained by the OUT parameter.
This parameter must be register by using the
registeroutParameter() mathod.
 INOUTIt is used for both purposes

52
CALLING THE STORED PROCEDURE
 The Connection interface provide the
prepareCall() method that is used to create the
CallableStatement object.

 The syntax to call stored procedure is ::>


{ call<procedure name>}

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);

ResultSet rs = stmt.executeQuery(“Select ….”);

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()

 ResultSet getPrimaryKeys(String catalog,String


schema,String table);

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()

 Int getGetColumnType( int col_index)

 String getTablenName()

 boolean isReadOnly(int colindex)

 boolean isWritable(int colindex)

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

You might also like