Sei sulla pagina 1di 59

Presentation by:

Chakradhar
JDBC
Java Data Base Connectivity
ODBC
It is dependent on O.S. as it exist in the form of .dll

connection
DRIVER 1 DB
Request connection
CLIENT DRIVER 2 DB
Application
connection
DRIVER 3 DB
ODBC Driver
Manager SERVER
JDBC
It is independent of O.S. which is specific to JRE.
JDBC is an API with set of classes and interfaces
present in package java.sql

JAVA
JDBC JRE DRIVER DB
APP

CLIENT SERVER

JAVA
JDBC JRE DRIVER DB
APP

CLIENT SERVER
JDBC Architecture
JDBC API Application

JDBC Driver Manager


JDBC.ODBC
JDBC JDBC BRIDGE
Driver A Driver B
ODBC

DB DB DB
JDBC
JDBC supports 4 types of Drivers
Thick Drivers:
1. JDBC-ODBC Bridge Driver.
2. Native-API Partly Java Driver
Thin Drivers:
3. Net-Protocol Fully Java Driver
4. Native-Protocol Fully Java Driver
JDBC-ODBC Bridge Driver
•A JDBC-ODBC bridge provides JDBC API
access via one or more ODBC drivers.
•some ODBC native code and in many cases
native database client code must be loaded
on each client machine that uses this type of
driver.
•It is appropriate when automatic installation
and downloading of a Java technology
application is not important.
JDBC-ODBC Bridge Driver

JDBC-ODBC BRIDGE

J O
JAVA D D
APP DB
B B
C C SERVER
CLIENT
Native-API Partly Java Driver

•This driver converts JDBC calls into


calls on the client API for Oracle,
SQLServer, Sybase, Informix, DB2, or
other DBMS.

•Like the bridge driver, this style of


driver requires that some binary code
be loaded on each client machine.
Native-API Partly Java Driver

J ORA
OCI CLE
JAVA D
App
B DB
SQL
Library
C Server

CLIENT SERVER
Net-Protocol Fully Java Driver
•This driver translates JDBC API calls into a
DBMS-independent net protocol which is then
translated to a DBMS protocol by a server.

•This net server middleware is able to connect


all of its Java technology-based clients to many
different databases.

•The specific protocol used depends on the


vendor. If vender changes then application will
not work.
Net-Protocol Fully Java Driver

JAVA JDBC ODBC DB


App Driver 1 Middle
ware OCI Ora
Appli cle
JAVA JDBC cation
DB
App Driver 2 SQL
Library Ser

APPLICATION
CLIENT SERVER SERVER
Native-Protocol Fully Java Driver
• This driver converts JDBC calls into the
network protocol used by DBMSs directly.
• This allows a direct call from the client to
the DBMS server and is a practical solution
for Intranet access.
• As protocols are proprietary to database
vendors, they will be the primary source
for this style of driver.
• Several database vendors have these in
progress.
Native-Protocol Fully Java Driver

JAVA JDBC Data


App Driver Base
PROTOCOL

user Sockets & Streams


Loading DriverManager
Syntax of loading the Class file

Class.forName(“DriverManagerClass”);

Example for Jdbc-Odbc bridge driver:


Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("jdbc:mysql://localhost/ejbdemo?use
r=user; password=pass”);
Loading DriverManager
Jdbc-Odbc Bridge : sun.jdbc.odbc.JdbcOdbcDriver

Oracle : oracle.jdbc.driver.OracleDriver

DB2 : COM.ibm.db2.jdbc.app.DB2Driver

Pointbase : com.pointbase.jdbc.jdbcUniversalDriver

Sybase : com.sybase.jdbc2.jdbc.SybDriver

SQL-Server : weblogic.jdbc.mssqlserver4.Driver
Data Source Name
• User DSN
–Available for user who creates and
stores in registry
• System DSN
–Available for all users and stores in
registry
• File DSN
–It stores in File
Connecting Through DSN
Connection con =
DriverManager.getConnection(“jdbc:odbc:dsnname”);

DriverManager.getConnection(“jdbc:odbc:dsnname”,
“username”, “password”);

DriverManager.getConnection("jdbc:oracle:oci“,
“username”, “password”);

DriverManager.getConnection("jdbc:oracle:thin:@ip
address:port:hoststring”, “username”, “password”)
Connection to DataBases
Jdbc-Odbc Bridge:may or may not need username, password
Jdbc:Odbc:Dsn1
Jdbc:Odbc:Dsn2
Oracle : needs username, password
jdbc:oracle:thin:@localhost:1521:orcl
jdbc:oracle:oci
DB2 :
jdbc:db2:mySource
Pointbase :
jdbc:pointbase://localhost:5008/Demo
Sybase :
jdbc:sybase:Tds:localhost:7009/Employee
SQL-Server : needs username, password
jdbc:weblogic:mssqlserver4:j2ee@localhost:1433
Connecting To Access
Example code to connect to Access type of database:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =
DriverManager.getConnection("Jdbc:Odbc:
DsnName");
Connecting To Oracle
Example code to connect to oracle Thick Driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =
DriverManager.getConnection("Jdbc:Odbc:
OraDsn","scott","tiger");
Connecting To Oracle
Example code to connect to oracle thin driver:

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con =
DriverManager.getConnection("jdbc:oracle:
thin:@localhost:1521:orcl","scott","tiger");
DatabaseMetaData
Provides the information about the Database

DatabaseMetaData mdata=con.getMetaData();

mdata.getDatabaseProductName()
mdata.getDatabaseProductVersion()
mdata.getDriverName()
mdata.supportsStoredProcedures()
Statements
1.Statement
It is used to execute SQL statements

2.Prepared Statement
Used to prepare statements with place
holders(?) to set the values at run time

3.Callable Statement
Used to execute functions or procedures
available in data base
Statement
Statement smt = con.createStatement();

ResultSet rs =
smt.executeQuery(“Select_Queries”);

int n =
smt.executeUpdate(“DML_Queries”);

boolean b =
smt.execute(“Other_Queries”);
ResultSet
• Is an Object which stores data of
the select statement result in
records and fields form.
• By default it is Forward Only and
Read Only.
• Result Set Navigation and updating
is possible from new API version
1.2 onwards.
ResultSet
• Navigating from one record to another
boolean b = rs.next()

• Extracting values from ResultSet is possible


either by Field Name or Field Index

int n=rs.getInt(int/String);
String s=rs.getString(int/String);
….
XXX x=rs.getXXX(int/String);
ResultSetMetaData
• It is Data about Data of ResultSet like field
names, no. of Columns etc.
ResultSetMetaData rsmd = rs.getMetaData();

int count = rsmd.getColumnCount();


Strting fname = rsmd.getColumnName(int index);
String alias = rsmd.getColumnLabel(int index);
int dn = rsmd.getColumnType(int index);
String dn = rsmd.getColumnTypeName(int index);
PreparedStatement
PreparedStatement ps =
con.prepareStatement(“Query with Place Holders”);

Example:
PreparedStatement ps =
con.prepareStatement(“select * from emp where
empno=?”);

PreparedStatement ps =
con.prepareStatement(“insert into emp(empno,
ename, sal, deptno) values(?,?,?,?)”);
PreparedStatement
Set values for place holders
ps.setInt(int, int);
ps.setString(int, String);
……..
ps.setXXX(int, XXX);

Executing the PreparedStatement


ResultSet rs=ps.executeQuery();
int n=ps.executeUpdate();
boolean b=ps.execute();
Callable Statement
• CallableStatement cs =
con.prepareCall(“{call fun/prod(?,?)}”);
con.prepareCall("{?=call fun/prod(?)}");

Example:
• CallableStatement cs =
con.prepareCall(“{call emp.insert(?,?,?)}”);
Callable Statement
Working with OUT/INOUT parameter
cs.registerOutparameter(int ind,int Types)
Example:
cs.registerOutParameter(1, java.sql.Types.TINYINT)
java.sql.Types
java.sql.Types.DATE java.sql.Types.DOUBLE
java.sql.Types.TIME java.sql.Types.FLOAT
java.sql.Types.VARCHAR java.sql.Types.INTEGER
java.sql.Types.TIMESTAMP java.sql.Types.NUMERIC
java.sql.Types. CHAR java.sql.Types.CLOB
java.sql.Types.BOOLEAN java.sql.Types.BLOB
CallableStatement
• Set values for place holders
cs.setInt(int, int);
cs.setString(int, String);
cs.setXXX(int, XXX);
• Executing the PreparedStatement
boolean b=cs.execute();
ResultSet rs=cs.getResultSet();
CallableStatement
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:orcl", "scott","tiger");
CallableStatement cs =
con.prepareCall("{?=call empSal(?)}");
cs.setInt(2, 7369);
cs.registerOutParameter(1,Types.INTEGER);
cs.executeUpdate();
int x=cs.getInt(1);
System.out.println(" The Value is "+ x);
con.close();
Properties Files
• This method is known as Loose coupled
method to work with the JDBC Application

JDBC Program
Properties File
Data Source
JDBC Properties File

User

Password
Properties Files
Properties Files(datasource.properties):-
datasource.name = Jdbc:Odbc:MyDsn
datasource.username = scott
datasource.password = tiger
datasource.query = select * from emp

To Use Property File:-


InputStream is =
ClassLoader.getSystemResourceAsStream
("datasource.properties");
Properties Files
Load File :-
Properties p = new Properties();
p.load (is);

Read the Properties:-


String dsn=p.getProperty("datasource.name");
String user=p.getProperty("datasource.username");
String pass=p.getProperty("datasource.password");
String query=p.getProperty("datasource.query");
JDBC 2.0
JDBC 2.0

This approach has several benefits, including


faster performance , re-usability and
improved security.

The New Feature of JDBC 2.0:-

-Supports advanced data types (SQL3 Data Types)


-Scrollable result sets
-Batch updates
Srollable ResultSet
JDBC 2.0 API allows to move a ResultSet’s
cursor backward as well as forward.

Statement stat=null
stat=con.createStatement(scrollability , updation)

Examples:
Statement st=
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Types of Result Sets
Based on the capabilities of scrollability and sensitivity to
changes, there are three types of result sets available with
the JDBC 2.0 core API.

• TYPE_FORWARD_ONLY
Nonscrollable, forward only
• TYPE_SCROLL_INSENSITIVE
Scrollable (forward, backward and particular row).
does not show changes to the database that are made
when it is open.
• TYPE_SCROLL_SENSITIVE
Scrollable (forward, backward and particular row).
Sensitive to changes made while it is open.
ResultSet Updation
A result set may have different update capabilities as

• CONCUR_READ_ONLY :-
– cannot be updated programmatically
– allow to read data but not to change it.
– no limit to the number of concurrent users unless the
DBMS or driver imposes one.
• CONCUR_UPDATABLE :-
– can be updated programmatically.
– use write-only locks so that only one user at a time has
access to a data item.
– eliminates the possibility of two or more users to
change the same data, thus ensuring database
consistency.
ResultSet Navigation
Navigation in ResultSet object is posible with the
different methods of ResultSet class

res.first()
res.last()
res.next()
res.afterLast()
res.beforeFirst()
res.absolute(4)
res.relative(1)
ResultSet Navigation
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin
:@localhost:1521:orcl", "scott","tiger");

Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_I
NSENSITIVE, ResultSet.CONCUR_UPDATABLE);

res=ps.executeQuery("select * from userData");


Batch Update
A batch update is a set of multiple update statements
that is submitted to the database for processing as a
batch.
Sending multiple update statements to the database
together as a unit can, in some situations, be much
more efficient than sending each update statement
separately.
This ability to send updates as a unit, referred to as
the batch update facility
This can be implemented with Statement , Prepared
Statement and Callable Statement interface.
Batch Update
addBatch(): To add SQL commands
clearBatch(): To empty the list
executeBatch(): To send all of the commands in the
list to the database

Statement stmt = con.createStatement();


stmt.addBatch("INSERT INTO COFFEES
VALUES(‘chakradhar', 49, 9.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES
VALUES('Honey', 49, 9.99, 0, 0)");
int[] updateCounts = stmt.executeBatch();
Advanced Data Types
The primary new data types include the

Blob (binary large object) photos


Clob (character large object) files
Array object
REF (object reference)
UDT (user-defined data type)
Handling Blob
File pic = new File("C:/images/mypic.jpg");

FileInputStream fis = new


FileInputStream(pic);

PreparedStatement ps =
con.prepareStatement(“insert into authors
values(?, ?)”) ;

ps.setString(1, “chakri");
ps.setBinaryStream(2, fis, (int)pic.length());
int n=ps.executeUpdate();
Reading Blob
PreparedStatement ps =
con.prepareStatement("SELECT photo FROM authors
WHERE author = ?") ;

ps.setString(1, “chakri");
ResultSet rs = ps.executeQuery() ;
rs.next() ;
Blob blob = rs.getBlob("photocolumn");
ImageIcon ic = new ImageIcon(blob.getBytes(1,
(int)blob.length()))
Jlabel l=new Jlabel(ic);
Handling Clob
PreparedStatement ps=
con.prepareStatement(“insert into messages
values(?,?)”)

File data = new File("C:/data/rjb.txt") ;


FileInputStream fis = new FileInputStream(data);

ps.setInt(1, 1);
ps.setAsciiStream(2, fis, (int)data.length());
int n=ps.executeUpdate();
Reading Clob
PreparedStatement ps =
con.prepareStatement(“select message
from messages where id = ?”);

ps.setInt(1, 1);
ResultSet rs = ps.executeQuery();
rs.next();
Clob cl = rs.getClob("message");
InputStreamReader in = new
InputStreamReader(cl.getAsciiStream());
Handling Arrays
Array implementation
Handling REF
REF (object reference)
Handling UDT

UDT (user-defined data type)


JDBC 3.0
JDBC API Version
JDBC API

JDBC JDBC
Core Standard
API Extension
1.1 2.0 onwards
JDBC 3.0
JNDI for naming databases
The Java Naming and Directory Interface
(JNDI) can be used in addition to the JDBC
driver manager to manage data sources and
connections. When an application uses
JNDI, it specifies a logical name that
identifies a particular database instance and
JDBC driver for accessing that database.
This has the advantage of making the
application code independent of a particular
JDBC driver and JDBC URL.
JDBC 3.0
Connection Pooling
This allows for a single connection cache that
spans the different JDBC drivers that may be in
use. Since creating and destroying database
connections is expensive, connection pooling
is important for achieving good performance,
especially for server applications.
Distributed transaction support
JDBC driver support for distributed
transactions allows developers to write
Enterprise JavaBeans that are transactional
across multiple DBMS servers.
JDBC 3.0
Rowsets
A rowset may or may not maintain an open
database connection. When a rowset is
‘disconnected’ from its data source, updates
performed on the rowset are propagated to
the underlying database using an optimistic
concurrency control algorithm.
JDBC 3.0
Interfaces and Classes
 javax.sql.ConnectionEvent  javax.sql.RowSet
 javax.sql.ConnectionEventL  javax.sql.RowSetEvent
istener  javax.sql.RowSetInternal
 javax.sql.ConnectionPoolDa  javax.sql.RowSetListener
taSource  javax.sql.RowSetMetaData
 javax.sql.DataSource  javax.sql.RowSetReader
 javax.sql.PooledConnection  javax.sql.RowSetWriter
 javax.sql.XAConnection
 javax.sql.XADataSource

Potrebbero piacerti anche