SlideShare a Scribd company logo
1 of 82
By Mumbai Academics
 JDBC
 JDBC is an alternative to ODBC and ADO that provides
database access to programs written in Java.
 JDBC drivers are available for most DBMS
products:
http://java.sun.com/products/jdbc
 JDBC
 Java API for connecting programs written in Java to the
data in relational databases
 The standard defined by Sun Microsystems, allowing
individual providers to implement and extend the
standard with their own JDBC drivers.
 Tasks of JDBC:
1) establishes a connection with a database
2) sends SQL statements
3) processes the results
 JDBC
 The JDBC API supports both two-tier and three-tier
models for database access.
 Two-tier model - a Java applet or application interacts
directly with the database.
 Three-tier model - introduces a middle-level server for
execution of business logic:
The middle tier to maintain control over data access.
The user can employ an easy-to-use higher-level API
which is translated by the middle tier into the
appropriate low-level calls.
 JDBC provides API or Protocol to interact
with different databases.
 With the help of JDBC driver we can
connect with different types of
databases.
 Driver is must needed for connection
establishment with any database.
 A driver works as an interface between
the
client and a database server.
 JDBC have so many classes and
interfaces that allow a Java application to
send request made by user to any
specific DBMS(Data Base Management
System).
 JDBC supports a wide level of portability.
 JDBC provides interfaces that are
compatible with java application
 Establish a connection
 Begin transaction
 Create a statement object
 Associate SQL with the statement object
 Provide values for statement parameters
 Execute the statement object
 Process the results
 End transaction
 Release resources
 Load the driver:
• The driver class libraries need to be in the
CLASSPATH for the Java compiler and for the
Java virtual machine.
• The most reliable way to load the driver into
the program is:
Class.forName(string).newInstance();
 Establish a connection to the database:
• A connection URL string includes the
literal jdbc:, followed by the name of
the driver and a URL to the database
String url =
"jdbc:oracle:thin:@localhost:1521:csodb";
jdbc “subprotocol”“subname” host port database
• Create a Connection object:
Connection con = DriverManager.getConnection(url,
dbUser,dbPassword);
 Begin the transaction
con.setTransactionIsolation(
Connection.TRANSACTION_SERIALIZABLE );
con.setAutoCommit( false );
 Create a statement object
Statement stmt = conn.createStatement();
 Associate SQL with the statement object
String queryString = "create table students "
+ "(name varchar(30), id int, phone char(9))";
 Process the statement:
Example statements:
ResultSet rs = stmt.executeQuery(querystring);
Int result = stmt.executeUpdate(updatestring);
ResultSetMetaData rsMeta = rs.getMetaData();
• Compiled queries can be processed via a
PreparedStatement object
• Stored procedures can be processed via a
CallableStatement object
 End transaction
con.commit();
con.rollback();
 Release resources
con.close();
Driver
Manager Connection Statement ResultSet
Driver
Database
Creates Creates Creates
SQL
Result
(tuples)
Establish
Link to DB
 Java Application talks
directly to the
database
 Accomplished
through the JDBC
driver which sends
commands directly to
the database
 Results sent back
directly to the
application
Application Space
Java Application
JDBC Driver
Database
SQL
Command
Result
Set
 JDBC driver sends
commands to a
middle tier, which
in turn sends
commands to
database.
 Results are sent
back to the middle
tier, which
communicates
them back to the
application
Application Space
Java Application
JDBC Driver
Database
SQL
Command
Result
Set
Application Server
(middle-tier)
Proprietary
Protocol
 The JDBC type 1 driver which is also
known as a JDBC-ODBC Bridge is a
convert JDBC methods into ODBC
function calls.
 Sun provides a JDBC-ODBC Bridge driver
by "sun.jdbc.odbc.JdbcOdbcDriver".
 The driver is a platform dependent
because it uses ODBC which is depends
on native libraries of the operating
system and also the driver needs other
installation for example, ODBC must be
installed on the computer and the
database must support ODBC Driver
 Type 1 is the simplest compare to all
other driver but it's a platform specific
i.e. only on Microsoft platform.
 The JDBC-ODBC Bridge is use only when
there is no PURE-JAVA driver available
for a particular database.
 Process:
Java Application -> JDBC APIs JDBC
Driver Manager —» Type 1 Driver —» ODBC
Driver —> Database library APIs —> Database
 Advantage:
(1) Connect to almost any database on any
system, for which ODBC driver is installed.
(2) It's an easy for installation as well as
easy(simplest) to use as compare the all other
driver.
 Disadvantage:
(1) The ODBC Driver needs to be installed on
the client machine.
(2) It's a not a purely platform independent
because its use ODBC which is depends on
native libraries of the operating system on
client machine.
(3) Not suitable for applets because the ODBC
driver needs to be installed on the client
machine.
 JDBC:ODBC ( mainly for Desktop
Applications)
Use bridging technology
Requires installation/configuration on
client machines
Not good for Web
 The JDBC type 2 driver is uses the
libraries of the database which is
available at client side and this driver
converts the JDBC method calls into
native calls of the database so this driver
is also known as a
Native-API driver.
 Process:
Java Application -> JDBC APIs JDBC
Driver Manager —» Type 2 Driver —» Vendor
Client Database library APIs —> Database
 Advantage:
(1) There is no implantation of JDBC-
ODBC Bridge so it's faster than a type 1
driver; hence the performance is better as
compare the type 1 driver
(JDBC-ODBC Bridge).
 Disadvantage
(1) On the client machine require the extra
installation because this driver uses the vendor
client libraries.
(2) The Client side software needed so cannot
use such type of driver in the web-based
application.
(3) Not all databases have the client side
library.
(4) This driver supports all JAVA applications
 eXCept applets.
 Native API Drivers (Vendor Specific
drivers)
Requires installation/configuration on
client machines
Used to leverage existing CLI libraries
Usually not thread-safe
Mostly obsolete now
 The JDBC type 3 driver uses the middle
tier(application server) between the
calling program and the database and
this middle tier converts JDBC method
calls into the vendor specific database
protocol and the same driver can be
used for multiple
databases also so it's also known as a
Network-Protocol driver as well as a JAVA
driver for database middleware.
 Process
Java Application —> JDBC APIs -> JDBC
Driver Manager —> Type 3 Driver —> Middleware
(Server)—> any Database
 Advantage:
(1) There is no need for the vendor database
library on the client machine because the
middleware is database independent and it
communicates with
client.
(2) Type 3 driver can be used in any web
application as well as on internet also because
there is no anv software require at client side.
(3) A single driver can handle any database at
client side so there is no need a Separate
driver for each database.
(4) The middleware server can also provide the
typical services such as connections, auditing,
load balancing, logging etc.
 Disadvantage:
(1) An Extra layer added, may be time
consuming.
(2) At the middleware develop the database
specific coding, may be increase complexity.
 Network API
Calls middleware server, usually on
database host
Very flexible & allows access to multiple
databases using one driver
Only need to download one driver
But it's another server application to
install and maintain.
 The JDBC type 4 driver converts JDBC
method calls directly into the vendor
specific database protocol and in
between do not need to be converted
any other formatted system so this is the
fastest way to communicate quires to
DBMS and it is completely written in
JAVA because of that this is also known as
the "direct to database Pure JAVA driver".
 Disadvantage:
(1) There is a separate driver needed for
each database at the client side.
(2) Drivers are Database dependent, as
different database vendors use different
network protocols.
 Network Protocol Driver (used for
Network based Applications)
Pure Java Drivers
Use Java networking libraries to talk
directly to database engines need to
download a new driver for each database
engine.
Alex Chaffee
JDBC
Type I
“Bridge”
Type II
“Native”
Type III
“Middleware”
Type IV
“Pure”
ODBC
ODBC
Driver
CLI (.lib)
Middleware
Server
Copyright © 1997 Alex Chaffee
DriverManager
Driver
Connection
Statement
ResultSet
Copyright © 1997 Alex Chaffee
jdbc:subprotocol:source
 each driver has its own subprotocol
 each subprotocol has its own syntax for
the source
jdbc:odbc:DataSource
• e.g. jdbc:odbc:Northwind
jdbc:msql://host[:port]/database
• e.g. jdbc:msql://foo.nowhere.com:4333/accounting
Copyright © 1997 Alex Chaffee
Loads database drivers, and manages the
connection between the application and
the driver
Connection getConnection
(String url, String user,
String password)
 Connects to given JDBC URL with given
user name and password
 Throws java.sql.SQLException
 returns a Connection object
Copyright © 1997 Alex Chaffee
Translates API calls into operations for a
specific data source
 A Connection represents a session with a specific
database or a session between an application and
a database
 Within the context of a Connection, SQL
statements are executed and results are returned.
 Can have multiple connections to a database
 Also provides “metadata” -- information about the
database, tables, and fields
 Also methods to deal with transactions
Copyright © 1997 Alex Chaffee
String url = "jdbc:odbc:Northwind";
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }
Copyright © 1997 Alex Chaffee
Statement createStatement()
• returns a new Statement object
PreparedStatement prepareStatement(String
sql)
• returns a new PreparedStatement object
CallableStatement prepareCall(String sql)
• returns a new CallableStatement object
 Why all these different kinds of statements?
Optimization.
Copyright © 1997 Alex Chaffee
 A Statement object is used for executing
a static SQL statement and obtaining the
results produced by it.
 An SQL Statement to perform a query or
update operation.
Copyright © 1997 Alex Chaffee
ResultSet executeQuery(String)
• Execute a SQL statement that returns a single
ResultSet.
int executeUpdate(String)
• Execute a SQL INSERT, UPDATE or DELETE
statement. Returns the number of rows changed.
boolean execute(String)
• Execute a SQL statement that may return multiple
results.
 Why all these different kinds of queries?
Optimization.
 A ResultSet provides access to a table of data
generated by executing a Statement.
 Logical set of columns and rows returned by
executing an SQL statement
 Only one ResultSet per Statement can be open
at once.
 The table rows are retrieved in sequence.
 A ResultSet maintains a cursor pointing to its
current row of data.
 The 'next' method moves the cursor to the next
row.
• you can’t rewind
Copyright © 1997 Alex Chaffee
 boolean next()
• activates the next row
• the first call to next() activates the first row
• returns false if there are no more rows
 void close()
• disposes of the ResultSet
• allows you to re-use the Statement that
created it
• automatically called by most Statement
methods
Copyright © 1997 Alex Chaffee
 Type getType(int columnIndex)
• returns the given field as the given type
• fields indexed starting at 1 (not 0)
 Type getType(String columnName)
• same, but uses name of field
• less efficient
 int findColumn(String columnName)
• looks up column index given column name
Copyright © 1997 Alex Chaffee
 String getString(int columnIndex)
 boolean getBoolean(int columnIndex)
 byte getByte(int columnIndex)
 short getShort(int columnIndex)
 int getInt(int columnIndex)
 long getLong(int columnIndex)
 float getFloat(int columnIndex)
 double getDouble(int columnIndex)
 Date getDate(int columnIndex)
 Time getTime(int columnIndex)
 Timestamp getTimestamp(int columnIndex)
Copyright © 1997 Alex Chaffee
 String getString(String columnName)
 boolean getBoolean(String columnName)
 byte getByte(String columnName)
 short getShort(String columnName)
 int getInt(String columnName)
 long getLong(String columnName)
 float getFloat(String columnName)
 double getDouble(String columnName)
 Date getDate(String columnName)
 Time getTime(String columnName)
 Timestamp getTimestamp(String columnName)
Copyright © 1997 Alex Chaffee
 In SQL, NULL means the field is empty
 Not the same as 0 or “”
 In JDBC, you must explicitly ask if a field
is null by calling ResultSet.isNull(column)
Copyright © 1997 Alex Chaffee
Employee ID Last Name First Name
1 Davolio Nancy
2 Fuller Andrew
3 Leverling Janet
4 Peacock Margaret
5 Buchanan Steven
Copyright © 1997 Alex Chaffee
Connection con =
DriverManager.getConnection(url, "alex",
"8675309");
Statement st = con.createStatement();
ResultSet results = st.executeQuery("SELECT
EmployeeID, LastName, FirstName FROM
Employees");
Copyright © 1997 Alex Chaffee
while (results.next()) {
int id = results.getInt(1);
String last = results.getString(2);
String first = results.getString(3);
System.out.println("" + id + ": " + first
+ " " + last);
}
st.close();
con.close();
Copyright © 1997 Alex Chaffee
SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Copyright © 1997 Alex Chaffee
 Times in SQL are notoriously unstandard
 Java defines three classes to help
 java.sql.Date
• year, month, day
 java.sql.Time
• hours, minutes, seconds
 java.sql.Timestamp
• year, month, day, hours, minutes, seconds,
nanoseconds
• usually use this one
Copyright © 1997 Alex Chaffee
 use executeUpdate if the SQL contains
“INSERT” or “UPDATE”
 Why isn’t it smart enough to parse the
SQL? Optimization.
 executeUpdate returns the number of
rows modified
 executeUpdate also used for “CREATE
TABLE” etc. (DDL)
Copyright © 1997 Alex Chaffee
 Transactions are not explicitly opened
and closed
 Instead, the connection has a state called
AutoCommit mode
 if AutoCommit is true, then every
statement is automatically committed
 default case: true
Copyright © 1997 Alex Chaffee
Connection.setAutoCommit(boolean)
 if AutoCommit is false, then every
statement is added to an ongoing
transaction
 you must explicitly commit or rollback
the transaction using
Connection.commit() and
Connection.rollback()
Copyright © 1997 Alex Chaffee
 Hint: for a large threaded database server, create a
Connection Manager object
 It is responsible for maintaining a certain number of
open connections to the database
 When your applications need a connection, they ask for
one from the CM’s pool
 Why? Because opening and closing connections takes
a long time
 Warning: the CM should always setAutoCommit(false)
when a connection is returned
Copyright © 1997 Alex Chaffee
 Prepared Statements
• SQL calls you make again and again
• allows driver to optimize (compile) queries
• created with Connection.prepareStatement()
 Stored Procedures
• written in DB-specific language
• stored inside database
• accesed with Connection.prepareCall()

Examples
Copyright © 1997 Alex Chaffee
 Connection:
• DatabaseMetaData getMetaData()
 ResultSet:
• ResultSetMetaData getMetaData()
Copyright © 1997 Alex Chaffee
 What's the number of columns in the
ResultSet?
 What's a column's name?
 What's a column's SQL type?
 What's the column's normal max width in
chars?
 What's the suggested column title for use
in printouts and displays?
 What's a column's number of decimal
digits?
Copyright © 1997 Alex Chaffee
 Does a column's case matter?
 Is the column a cash value?
 Will a write on the column definitely
succeed?
 Can you put a NULL in this column?
 Is a column definitely not writable?
 Can the column be used in a where
clause?
 Is the column a signed number?
 Is it possible for a write on the column to
succeed?
 and so on...
Copyright © 1997 Alex Chaffee
 What tables are available?
 What's our user name as known to the
database?
 Is the database in read-only mode?
 If table correlation names are supported,
are they restricted to be different from
the names of the tables?
 and so on…
 Scrollable result set
 Batch updates
 Advanced data types
• Blobs, objects, structured types
 Rowsets
• Persistent JavaBeans
 JNDI
 Connection Pooling
 Distributed transactions via JTS
 In JDBC1.0, result sets could be
navigated in only one direction (forward)
and starting at only one point (first row)
 Since JDBC 2.0, the cursor can be
manipulated as if it were a array index
 Methods exist for reading both forward
and backward, for starting from any row,
and for testing the current cursor
location.
boolean next ( ) Advances the cursor to the next row.
boolean previous ( ) Moves the cursor back one row.
boolean first ( ) Moves the cursor to the first row.
boolean last ( ) Moves the cursor to the last row.
void beforeFirst ( ) Moves the cursor before the first
row, usually in anticipation of
calling next ( )
void afterLast ( ) Moves the cursor after the last row,
usually in anticipation of
calling previous ( )
boolean Moves the cursor to the specified
absolute (int row) row. Specifying a negative number
moves the cursor relative to the
end of the result set;
boolean Moves the cursor forward or
relative (int row) backward the number of rows
specified.
boolean True if the cursor is before the
isBeforeFirst ( ) first row.
boolean True if the cursor is after the
isAfterLast ( ) last row.
boolean isFirst ( ) True if the cursor is positioned on
the first row.
boolean isLast ( ) True if the cursor is positioned on
the last row.
 Statement object created with parameters to
indicate specific capabilities
 Connection.createStatement() method can have
up to three parameters:
• resultSetType – type of scrolling to be used
• resultSetConcurrency – indicates whether the result
set can be updated
• resultSetHoldability – specifies whether to close
cursors when a commit is done
 Example
• stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
 Cursor Related Constants
• TYPE_FORWARD_ONLY
 JDBC 1.0-style navigation in which the cursor
starts at the first row and can only move forward.
• TYPE_SCROLL_INSENSITIVE
 All cursor positioning methods are enabled; the
result set doesn’t reflect changes made by others
in the underlying table.
• TYPE_SCROLL_SENSITIVE
 All cursor positioning methods are enabled the
result set reflects changes made by others in the
underlying table.
 Updating Record Sets
• CONCUR_READ_ONLY
 The results set won’t be updatable
• CONCUR_UPDATABLE
 Rows can be added and deleted, and columns
can be updated.
 Closing Cursors
• HOLD_CURSORS_OVER_COMMIT
 Do not close cursors after a commit is done.
• CLOSE_COURSORS_AT_COMMIT
 Close cursors when a commit is done.

More Related Content

What's hot

What's hot (20)

Java Swing
Java SwingJava Swing
Java Swing
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class library
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Java logging
Java loggingJava logging
Java logging
 
JDBC
JDBCJDBC
JDBC
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Java Logging
Java LoggingJava Logging
Java Logging
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 

Viewers also liked

Viewers also liked (8)

Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 

Similar to JDBC Types: Bridge, Native, Middleware & Pure Java Drivers

Similar to JDBC Types: Bridge, Native, Middleware & Pure Java Drivers (20)

Jdbc
JdbcJdbc
Jdbc
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Jdbc driver types
Jdbc driver typesJdbc driver types
Jdbc driver types
 
jdbc document
jdbc documentjdbc document
jdbc document
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
jdbc
jdbcjdbc
jdbc
 
jdbc-130913021409-phpapp01000988www.pptx
jdbc-130913021409-phpapp01000988www.pptxjdbc-130913021409-phpapp01000988www.pptx
jdbc-130913021409-phpapp01000988www.pptx
 
Jdbc driver types
Jdbc driver typesJdbc driver types
Jdbc driver types
 
JDBC Driver Types
JDBC Driver TypesJDBC Driver Types
JDBC Driver Types
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
 
Advanced JAVA
Advanced JAVAAdvanced JAVA
Advanced JAVA
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 

More from Mumbai Academisc

More from Mumbai Academisc (20)

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Ieee java projects list
Ieee java projects list Ieee java projects list
Ieee java projects list
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects list
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects list
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai Academics
 
Web based development
Web based developmentWeb based development
Web based development
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Java tutorial part 2
Java tutorial part 2Java tutorial part 2
Java tutorial part 2
 
Engineering
EngineeringEngineering
Engineering
 
Jsp
JspJsp
Jsp
 

Recently uploaded

Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

JDBC Types: Bridge, Native, Middleware & Pure Java Drivers

  • 2.  JDBC  JDBC is an alternative to ODBC and ADO that provides database access to programs written in Java.  JDBC drivers are available for most DBMS products: http://java.sun.com/products/jdbc
  • 3.  JDBC  Java API for connecting programs written in Java to the data in relational databases  The standard defined by Sun Microsystems, allowing individual providers to implement and extend the standard with their own JDBC drivers.  Tasks of JDBC: 1) establishes a connection with a database 2) sends SQL statements 3) processes the results
  • 4.  JDBC  The JDBC API supports both two-tier and three-tier models for database access.  Two-tier model - a Java applet or application interacts directly with the database.  Three-tier model - introduces a middle-level server for execution of business logic: The middle tier to maintain control over data access. The user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls.
  • 5.
  • 6.  JDBC provides API or Protocol to interact with different databases.  With the help of JDBC driver we can connect with different types of databases.  Driver is must needed for connection establishment with any database.  A driver works as an interface between the client and a database server.
  • 7.  JDBC have so many classes and interfaces that allow a Java application to send request made by user to any specific DBMS(Data Base Management System).  JDBC supports a wide level of portability.  JDBC provides interfaces that are compatible with java application
  • 8.
  • 9.  Establish a connection  Begin transaction  Create a statement object  Associate SQL with the statement object  Provide values for statement parameters  Execute the statement object  Process the results  End transaction  Release resources
  • 10.  Load the driver: • The driver class libraries need to be in the CLASSPATH for the Java compiler and for the Java virtual machine. • The most reliable way to load the driver into the program is: Class.forName(string).newInstance();
  • 11.  Establish a connection to the database: • A connection URL string includes the literal jdbc:, followed by the name of the driver and a URL to the database String url = "jdbc:oracle:thin:@localhost:1521:csodb"; jdbc “subprotocol”“subname” host port database • Create a Connection object: Connection con = DriverManager.getConnection(url, dbUser,dbPassword);
  • 12.  Begin the transaction con.setTransactionIsolation( Connection.TRANSACTION_SERIALIZABLE ); con.setAutoCommit( false );  Create a statement object Statement stmt = conn.createStatement();  Associate SQL with the statement object String queryString = "create table students " + "(name varchar(30), id int, phone char(9))";
  • 13.  Process the statement: Example statements: ResultSet rs = stmt.executeQuery(querystring); Int result = stmt.executeUpdate(updatestring); ResultSetMetaData rsMeta = rs.getMetaData(); • Compiled queries can be processed via a PreparedStatement object • Stored procedures can be processed via a CallableStatement object
  • 15. Driver Manager Connection Statement ResultSet Driver Database Creates Creates Creates SQL Result (tuples) Establish Link to DB
  • 16.  Java Application talks directly to the database  Accomplished through the JDBC driver which sends commands directly to the database  Results sent back directly to the application Application Space Java Application JDBC Driver Database SQL Command Result Set
  • 17.  JDBC driver sends commands to a middle tier, which in turn sends commands to database.  Results are sent back to the middle tier, which communicates them back to the application Application Space Java Application JDBC Driver Database SQL Command Result Set Application Server (middle-tier) Proprietary Protocol
  • 18.  The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC methods into ODBC function calls.  Sun provides a JDBC-ODBC Bridge driver by "sun.jdbc.odbc.JdbcOdbcDriver".
  • 19.  The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example, ODBC must be installed on the computer and the database must support ODBC Driver
  • 20.  Type 1 is the simplest compare to all other driver but it's a platform specific i.e. only on Microsoft platform.  The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a particular database.
  • 21.
  • 22.  Process: Java Application -> JDBC APIs JDBC Driver Manager —» Type 1 Driver —» ODBC Driver —> Database library APIs —> Database  Advantage: (1) Connect to almost any database on any system, for which ODBC driver is installed. (2) It's an easy for installation as well as easy(simplest) to use as compare the all other driver.
  • 23.  Disadvantage: (1) The ODBC Driver needs to be installed on the client machine. (2) It's a not a purely platform independent because its use ODBC which is depends on native libraries of the operating system on client machine. (3) Not suitable for applets because the ODBC driver needs to be installed on the client machine.
  • 24.  JDBC:ODBC ( mainly for Desktop Applications) Use bridging technology Requires installation/configuration on client machines Not good for Web
  • 25.  The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver converts the JDBC method calls into native calls of the database so this driver is also known as a Native-API driver.
  • 26.
  • 27.  Process: Java Application -> JDBC APIs JDBC Driver Manager —» Type 2 Driver —» Vendor Client Database library APIs —> Database  Advantage: (1) There is no implantation of JDBC- ODBC Bridge so it's faster than a type 1 driver; hence the performance is better as compare the type 1 driver (JDBC-ODBC Bridge).
  • 28.  Disadvantage (1) On the client machine require the extra installation because this driver uses the vendor client libraries. (2) The Client side software needed so cannot use such type of driver in the web-based application. (3) Not all databases have the client side library. (4) This driver supports all JAVA applications  eXCept applets.
  • 29.  Native API Drivers (Vendor Specific drivers) Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now
  • 30.  The JDBC type 3 driver uses the middle tier(application server) between the calling program and the database and this middle tier converts JDBC method calls into the vendor specific database protocol and the same driver can be used for multiple databases also so it's also known as a Network-Protocol driver as well as a JAVA driver for database middleware.
  • 31.
  • 32.  Process Java Application —> JDBC APIs -> JDBC Driver Manager —> Type 3 Driver —> Middleware (Server)—> any Database  Advantage: (1) There is no need for the vendor database library on the client machine because the middleware is database independent and it communicates with client.
  • 33. (2) Type 3 driver can be used in any web application as well as on internet also because there is no anv software require at client side. (3) A single driver can handle any database at client side so there is no need a Separate driver for each database. (4) The middleware server can also provide the typical services such as connections, auditing, load balancing, logging etc.
  • 34.  Disadvantage: (1) An Extra layer added, may be time consuming. (2) At the middleware develop the database specific coding, may be increase complexity.
  • 35.  Network API Calls middleware server, usually on database host Very flexible & allows access to multiple databases using one driver Only need to download one driver But it's another server application to install and maintain.
  • 36.  The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in between do not need to be converted any other formatted system so this is the fastest way to communicate quires to DBMS and it is completely written in JAVA because of that this is also known as the "direct to database Pure JAVA driver".
  • 37.
  • 38.  Disadvantage: (1) There is a separate driver needed for each database at the client side. (2) Drivers are Database dependent, as different database vendors use different network protocols.
  • 39.  Network Protocol Driver (used for Network based Applications) Pure Java Drivers Use Java networking libraries to talk directly to database engines need to download a new driver for each database engine.
  • 40. Alex Chaffee JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC ODBC Driver CLI (.lib) Middleware Server
  • 41. Copyright © 1997 Alex Chaffee DriverManager Driver Connection Statement ResultSet
  • 42. Copyright © 1997 Alex Chaffee jdbc:subprotocol:source  each driver has its own subprotocol  each subprotocol has its own syntax for the source jdbc:odbc:DataSource • e.g. jdbc:odbc:Northwind jdbc:msql://host[:port]/database • e.g. jdbc:msql://foo.nowhere.com:4333/accounting
  • 43. Copyright © 1997 Alex Chaffee Loads database drivers, and manages the connection between the application and the driver Connection getConnection (String url, String user, String password)  Connects to given JDBC URL with given user name and password  Throws java.sql.SQLException  returns a Connection object
  • 44. Copyright © 1997 Alex Chaffee Translates API calls into operations for a specific data source
  • 45.  A Connection represents a session with a specific database or a session between an application and a database  Within the context of a Connection, SQL statements are executed and results are returned.  Can have multiple connections to a database  Also provides “metadata” -- information about the database, tables, and fields  Also methods to deal with transactions
  • 46. Copyright © 1997 Alex Chaffee String url = "jdbc:odbc:Northwind"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
  • 47. Copyright © 1997 Alex Chaffee Statement createStatement() • returns a new Statement object PreparedStatement prepareStatement(String sql) • returns a new PreparedStatement object CallableStatement prepareCall(String sql) • returns a new CallableStatement object  Why all these different kinds of statements? Optimization.
  • 48. Copyright © 1997 Alex Chaffee  A Statement object is used for executing a static SQL statement and obtaining the results produced by it.  An SQL Statement to perform a query or update operation.
  • 49. Copyright © 1997 Alex Chaffee ResultSet executeQuery(String) • Execute a SQL statement that returns a single ResultSet. int executeUpdate(String) • Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) • Execute a SQL statement that may return multiple results.  Why all these different kinds of queries? Optimization.
  • 50.  A ResultSet provides access to a table of data generated by executing a Statement.  Logical set of columns and rows returned by executing an SQL statement  Only one ResultSet per Statement can be open at once.  The table rows are retrieved in sequence.  A ResultSet maintains a cursor pointing to its current row of data.  The 'next' method moves the cursor to the next row. • you can’t rewind
  • 51. Copyright © 1997 Alex Chaffee  boolean next() • activates the next row • the first call to next() activates the first row • returns false if there are no more rows  void close() • disposes of the ResultSet • allows you to re-use the Statement that created it • automatically called by most Statement methods
  • 52. Copyright © 1997 Alex Chaffee  Type getType(int columnIndex) • returns the given field as the given type • fields indexed starting at 1 (not 0)  Type getType(String columnName) • same, but uses name of field • less efficient  int findColumn(String columnName) • looks up column index given column name
  • 53. Copyright © 1997 Alex Chaffee  String getString(int columnIndex)  boolean getBoolean(int columnIndex)  byte getByte(int columnIndex)  short getShort(int columnIndex)  int getInt(int columnIndex)  long getLong(int columnIndex)  float getFloat(int columnIndex)  double getDouble(int columnIndex)  Date getDate(int columnIndex)  Time getTime(int columnIndex)  Timestamp getTimestamp(int columnIndex)
  • 54. Copyright © 1997 Alex Chaffee  String getString(String columnName)  boolean getBoolean(String columnName)  byte getByte(String columnName)  short getShort(String columnName)  int getInt(String columnName)  long getLong(String columnName)  float getFloat(String columnName)  double getDouble(String columnName)  Date getDate(String columnName)  Time getTime(String columnName)  Timestamp getTimestamp(String columnName)
  • 55. Copyright © 1997 Alex Chaffee  In SQL, NULL means the field is empty  Not the same as 0 or “”  In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)
  • 56. Copyright © 1997 Alex Chaffee Employee ID Last Name First Name 1 Davolio Nancy 2 Fuller Andrew 3 Leverling Janet 4 Peacock Margaret 5 Buchanan Steven
  • 57. Copyright © 1997 Alex Chaffee Connection con = DriverManager.getConnection(url, "alex", "8675309"); Statement st = con.createStatement(); ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees");
  • 58. Copyright © 1997 Alex Chaffee while (results.next()) { int id = results.getInt(1); String last = results.getString(2); String first = results.getString(3); System.out.println("" + id + ": " + first + " " + last); } st.close(); con.close();
  • 59. Copyright © 1997 Alex Chaffee SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp
  • 60. Copyright © 1997 Alex Chaffee  Times in SQL are notoriously unstandard  Java defines three classes to help  java.sql.Date • year, month, day  java.sql.Time • hours, minutes, seconds  java.sql.Timestamp • year, month, day, hours, minutes, seconds, nanoseconds • usually use this one
  • 61. Copyright © 1997 Alex Chaffee  use executeUpdate if the SQL contains “INSERT” or “UPDATE”  Why isn’t it smart enough to parse the SQL? Optimization.  executeUpdate returns the number of rows modified  executeUpdate also used for “CREATE TABLE” etc. (DDL)
  • 62. Copyright © 1997 Alex Chaffee  Transactions are not explicitly opened and closed  Instead, the connection has a state called AutoCommit mode  if AutoCommit is true, then every statement is automatically committed  default case: true
  • 63. Copyright © 1997 Alex Chaffee Connection.setAutoCommit(boolean)  if AutoCommit is false, then every statement is added to an ongoing transaction  you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()
  • 64. Copyright © 1997 Alex Chaffee  Hint: for a large threaded database server, create a Connection Manager object  It is responsible for maintaining a certain number of open connections to the database  When your applications need a connection, they ask for one from the CM’s pool  Why? Because opening and closing connections takes a long time  Warning: the CM should always setAutoCommit(false) when a connection is returned
  • 65. Copyright © 1997 Alex Chaffee  Prepared Statements • SQL calls you make again and again • allows driver to optimize (compile) queries • created with Connection.prepareStatement()  Stored Procedures • written in DB-specific language • stored inside database • accesed with Connection.prepareCall()
  • 66.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72. Copyright © 1997 Alex Chaffee  Connection: • DatabaseMetaData getMetaData()  ResultSet: • ResultSetMetaData getMetaData()
  • 73. Copyright © 1997 Alex Chaffee  What's the number of columns in the ResultSet?  What's a column's name?  What's a column's SQL type?  What's the column's normal max width in chars?  What's the suggested column title for use in printouts and displays?  What's a column's number of decimal digits?
  • 74. Copyright © 1997 Alex Chaffee  Does a column's case matter?  Is the column a cash value?  Will a write on the column definitely succeed?  Can you put a NULL in this column?  Is a column definitely not writable?  Can the column be used in a where clause?  Is the column a signed number?  Is it possible for a write on the column to succeed?  and so on...
  • 75. Copyright © 1997 Alex Chaffee  What tables are available?  What's our user name as known to the database?  Is the database in read-only mode?  If table correlation names are supported, are they restricted to be different from the names of the tables?  and so on…
  • 76.  Scrollable result set  Batch updates  Advanced data types • Blobs, objects, structured types  Rowsets • Persistent JavaBeans  JNDI  Connection Pooling  Distributed transactions via JTS
  • 77.  In JDBC1.0, result sets could be navigated in only one direction (forward) and starting at only one point (first row)  Since JDBC 2.0, the cursor can be manipulated as if it were a array index  Methods exist for reading both forward and backward, for starting from any row, and for testing the current cursor location.
  • 78. boolean next ( ) Advances the cursor to the next row. boolean previous ( ) Moves the cursor back one row. boolean first ( ) Moves the cursor to the first row. boolean last ( ) Moves the cursor to the last row. void beforeFirst ( ) Moves the cursor before the first row, usually in anticipation of calling next ( ) void afterLast ( ) Moves the cursor after the last row, usually in anticipation of calling previous ( ) boolean Moves the cursor to the specified absolute (int row) row. Specifying a negative number moves the cursor relative to the end of the result set;
  • 79. boolean Moves the cursor forward or relative (int row) backward the number of rows specified. boolean True if the cursor is before the isBeforeFirst ( ) first row. boolean True if the cursor is after the isAfterLast ( ) last row. boolean isFirst ( ) True if the cursor is positioned on the first row. boolean isLast ( ) True if the cursor is positioned on the last row.
  • 80.  Statement object created with parameters to indicate specific capabilities  Connection.createStatement() method can have up to three parameters: • resultSetType – type of scrolling to be used • resultSetConcurrency – indicates whether the result set can be updated • resultSetHoldability – specifies whether to close cursors when a commit is done  Example • stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
  • 81.  Cursor Related Constants • TYPE_FORWARD_ONLY  JDBC 1.0-style navigation in which the cursor starts at the first row and can only move forward. • TYPE_SCROLL_INSENSITIVE  All cursor positioning methods are enabled; the result set doesn’t reflect changes made by others in the underlying table. • TYPE_SCROLL_SENSITIVE  All cursor positioning methods are enabled the result set reflects changes made by others in the underlying table.
  • 82.  Updating Record Sets • CONCUR_READ_ONLY  The results set won’t be updatable • CONCUR_UPDATABLE  Rows can be added and deleted, and columns can be updated.  Closing Cursors • HOLD_CURSORS_OVER_COMMIT  Do not close cursors after a commit is done. • CLOSE_COURSORS_AT_COMMIT  Close cursors when a commit is done.

Editor's Notes

  1. Copyright © 1997 Alex Chaffee
  2. Copyright © 1997 Alex Chaffee
  3. Copyright © 1997 Alex Chaffee
  4. Copyright © 1997 Alex Chaffee
  5. Copyright © 1997 Alex Chaffee
  6. Copyright © 1997 Alex Chaffee
  7. Copyright © 1997 Alex Chaffee
  8. Copyright © 1997 Alex Chaffee
  9. Copyright © 1997 Alex Chaffee
  10. Copyright © 1997 Alex Chaffee
  11. Copyright © 1997 Alex Chaffee
  12. Copyright © 1997 Alex Chaffee
  13. Copyright © 1997 Alex Chaffee
  14. Copyright © 1997 Alex Chaffee
  15. Copyright © 1997 Alex Chaffee
  16. Copyright © 1997 Alex Chaffee
  17. Copyright © 1997 Alex Chaffee
  18. Copyright © 1997 Alex Chaffee
  19. Copyright © 1997 Alex Chaffee
  20. Copyright © 1997 Alex Chaffee
  21. Copyright © 1997 Alex Chaffee
  22. Copyright © 1997 Alex Chaffee
  23. Copyright © 1997 Alex Chaffee
  24. Copyright © 1997 Alex Chaffee
  25. Copyright © 1997 Alex Chaffee
  26. Copyright © 1997 Alex Chaffee
  27. Copyright © 1997 Alex Chaffee
  28. Copyright © 1997 Alex Chaffee
  29. Copyright © 1997 Alex Chaffee
  30. Copyright © 1997 Alex Chaffee
  31. Copyright © 1997 Alex Chaffee
  32. Copyright © 1997 Alex Chaffee
  33. Copyright © 1997 Alex Chaffee