Java Data Base Connectivity: WWW - Twoengineers.co - in
Java Data Base Connectivity: WWW - Twoengineers.co - in
Java Data Base Connectivity: WWW - Twoengineers.co - in
www.twoengineers.co.in
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
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
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.
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
Class.forName(“DriverManagerClass”);
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","ti
ger");
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
Navigatingfrom one record to another
boolean b = rs.next()
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();
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);
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
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
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:@l
ocalhost:1521:orcl", "scott","tiger");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSE
NSITIVE, ResultSet.CONCUR_UPDATABLE);
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(?,?)”)
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
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