presentationjdbc_daiict
TRANSCRIPT
-
8/9/2019 PresentationJDBC_DAIICT
1/127
Wel ComeDhiraj Thakkar (MD, Royal Technosoft)
RTIM-Merchant Navy,MS-IT,J2EE Application 3 years
1 Year Webpshere Portal Server
-
8/9/2019 PresentationJDBC_DAIICT
2/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Course Map
JDBC Introduction to Java Class.
A Simple java Hello World application. Introduction to JDBC. Type of Drivers (Type 1, Type 2, Type 3, Type 4) JDBC Classes for creating a Connection
Connection Troubles. Class Not Found Driver Not Found
Basic Database Access
-
8/9/2019 PresentationJDBC_DAIICT
3/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Course Map
Sql Data Types and Java Data Types(must include BLOB, CLOB, ARRAY introduction).
Statements, PreparedStatements, Callable Statements.
Result Set and its types.
Result Set navigation.
Java example to retrieve and display the data from emptable.
Java example to Insert employee record into emp table.
-
8/9/2019 PresentationJDBC_DAIICT
4/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Course Map
Java example to Update employee record in the emp table. Java example to Delete employee record from the emp table. Emphasis to be given on storing and retrieval of date type. Binding parameters in statements & prepared statements.
Example java class for storing a image file as a Blob Example java class for storing a text file as a clob Example java class for retrieving the above two large objects. Meta Data Result Set Meta-Data Introduction to JSP Technology
Converting the above examples made on java classes to JSP anddisplaying them. (Need not to cover installation of Tomcat etc.)
Connection Pooling
-
8/9/2019 PresentationJDBC_DAIICT
5/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Tools & Tech
Basic Tools Requirement
Eclipse 3.0 or up
J2sdk 1.5 Toad (Interface to oracle) Tomcat 5.0 Dream Weaver(JSP,HTML)
-
8/9/2019 PresentationJDBC_DAIICT
6/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Why Java?
Write once, run anywhere
Multiple client and server platforms
Object-relational mapping
databases optimized for searching/indexing objects optimized for engineering/flexibility
Network independence
Works across Internet Protocol
Database independence
Java can access any database vendor
Ease of administration
zero-install client
-
8/9/2019 PresentationJDBC_DAIICT
7/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Hello World
// HelloWorld.java: Hello World program
import java.lang.*;class HelloWorld
{
public static void main(String args[])
{
System.out.println(Hello World);
}
}
-
8/9/2019 PresentationJDBC_DAIICT
8/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Hello World: Java and C
// HelloWorld.java: Hello World program
import java.lang.*;
class HelloWorld
{
public static void main(String args[])
{
System.out.println(Hello World);
}}
/* helloworld.c: Hello World program */
#define
void main(int argc, char *argv[])
{
printf(Hello World\n);
}
S1:S2:
S3:
S4:
S6:
-
8/9/2019 PresentationJDBC_DAIICT
9/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Program Processing
Compilation# javac HelloWorld.java
results in HelloWorld.class
Execution
# java HelloWorld
Hello World
-
8/9/2019 PresentationJDBC_DAIICT
10/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
public static void main(String args[])
public: The keyword public is an accessspecifier that declares the main method asunprotected.
static: It says this method belongs to the entireclass and NOT a part of any objects of class.The main must always be declared static sincethe interpreter users this before any objects are
created. void: The type modifier that states that main
does not return any value.
-
8/9/2019 PresentationJDBC_DAIICT
11/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
System.out.println(Hello World);
java.lang.*
All classes/items in lang package of java package.
System is really the java.lang.System class.
This class has a public static field called outwhich is an instance of the java.io.PrintStreamclass. So when we write System.out.println(),
we are really invoking the println() method ofthe out field of the java.lang.System class.
-
8/9/2019 PresentationJDBC_DAIICT
12/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Java Program Structure
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Declarations
Main Method Class{}
-
8/9/2019 PresentationJDBC_DAIICT
13/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Database Architectures
Two-tier
Three-tier
N-tier
-
8/9/2019 PresentationJDBC_DAIICT
14/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Two-Tier Architecture
Client connects directly to server
e.g. HTTP, email
Pro: simple
client-side scripting offloads work onto the
client Con:
fat client
inflexible
-
8/9/2019 PresentationJDBC_DAIICT
15/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Three-Tier Architecture
Application Server sits between clientand database
-
8/9/2019 PresentationJDBC_DAIICT
16/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Three-Tier Pros
flexible: can change one part withoutaffecting others
can connect to different databaseswithout changing code
specialization: presentation / business
logic / data management can cache queries
can implement proxies and firewalls
-
8/9/2019 PresentationJDBC_DAIICT
17/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Three-Tier Cons
higher complexity
higher maintenance
lower network efficiency more parts to configure (and buy)
-
8/9/2019 PresentationJDBC_DAIICT
18/127
-
8/9/2019 PresentationJDBC_DAIICT
19/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
N-Tier Architecture
Design your application using as manytiers as you need
Use Object-Oriented Design techniques Put the various components on whatever
host makes sense
Java allows N-Tier Architecture, especiallywith RMI and JDBC
-
8/9/2019 PresentationJDBC_DAIICT
20/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Database Technologies
Hierarchical obsolete (in a manner of speaking)
any specialized file format can be called a hierarchical DB
Relational (aka SQL) (RDBMS) row, column
most popular
Object-relational DB (ORDBMS) add inheritance, blobs to RDB
NOT object-oriented -- object is mostly a marketing term
Object-oriented DB (OODB) data stored as objects
high-performance for OO data models
-
8/9/2019 PresentationJDBC_DAIICT
21/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Goals
SQL-Level
100% Pure Java
Keep it simple High-performance
Leverage existing database technology
why reinvent the wheel?
Use strong, static typing wherever possible
Use multiple methods to express multiplefunctionality
-
8/9/2019 PresentationJDBC_DAIICT
22/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Ancestry
X/OPEN
ODBCJDBC
-
8/9/2019 PresentationJDBC_DAIICT
23/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Architecture
Application JDBC Driver
Java code calls JDBC library JDBC loads a driver
Driver talks to a particular database
Can have more than one driver -> more thanone database
Ideal: can change database engines withoutchanging any application code
-
8/9/2019 PresentationJDBC_DAIICT
24/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Drivers
Type I: Bridge
Type II: Native
Type III: Middleware Type IV: Pure
-
8/9/2019 PresentationJDBC_DAIICT
25/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Overall Architecture
-
8/9/2019 PresentationJDBC_DAIICT
26/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Introducing JDBC
According to Sun, JDBC is not anacronym, but is commonly misinterpreted
to mean Java DataBase Connectivity Supports ANSI SQL 92 Entry Level
-
8/9/2019 PresentationJDBC_DAIICT
27/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
The Standard Query Language(SQL)
Composed of two categories:
Data Manipulation Language (DML)
used to manipulate the data select
delete
update
Data Definition Language (DDL) create database
create table
drop database
-
8/9/2019 PresentationJDBC_DAIICT
28/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Manipulation Language
SELECT - query the database
select * from customer where id > 1001
INSERT - adds new rows to a table. Insert into customer values (1009, John
Doe)
DELTE - removes a specified row delete
UPDATE - modifies an existing row
update customers set amount = 10 whereid > 1003
-
8/9/2019 PresentationJDBC_DAIICT
29/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Definition Language
CREATE DATABASE - allows you to createa database
CREATE TABLE - allows you to create atable definition in a database
DROP TABLE - removes a table from a
databaseALTER TABLE - modifies the definition of
a table in a database
-
8/9/2019 PresentationJDBC_DAIICT
30/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Framework
The JDBC driver manager
The JDBC driver
-
8/9/2019 PresentationJDBC_DAIICT
31/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
The JDBC Driver Manager
Management layer of JDBC, interfaces between theclient and the driver.
Keeps a hash list of available drivers
Manages driver login time limits and printing of logand tracing messages
Secure because manager will only allow drivers thatcome from local file system or the same initial classloader requesting a connection
Most popular function:
Connection getConnection(url, id, passwd);
-
8/9/2019 PresentationJDBC_DAIICT
32/127
-
8/9/2019 PresentationJDBC_DAIICT
33/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Drivers (Fig.)
JDBC
Type I
Bridge
Type II
Native
Type III
Middleware
Type IV
Pure
ODBCODBC
Driver
CLI (.lib)
Middleware
Server
-
8/9/2019 PresentationJDBC_DAIICT
34/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 1 DriversJDBC-ODBC Bridges
JDBC driver translates call into ODBC andredirects ODBC call to an ODBC driver on
the DBMS ODBC binary code must exist on every
client
Translation layer compromises executionspeed to small degree
-
8/9/2019 PresentationJDBC_DAIICT
35/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 1 DriversJDBC-ODBC Bridges
The type 1 driver, JDBC-ODBC Bridge, translates all JDBC callsinto ODBC (Open DataBase Connectivity) calls and sends themto the ODBC driver. As such, the ODBC driver, as well as, inmany cases, the client database code, must be present on theclient machine. Figure 1 shows a typical JDBC-ODBC Bridge
environment.
Diagram
-
8/9/2019 PresentationJDBC_DAIICT
36/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 2 DriversNative-API + Java Driver
Java driver makes JNI calls on the client API (usuallywritten in C or C++)
eg: Sybase dblib or ctlib
eg: Oracle Call Interface libs (OCI) Requires client-side code to be installed
Often the fastest solution available
Native drivers are usually delivered by DBMS vendor
bug in driver can crash JVMs
Example: JDBC=>Sybase dblib or ctlib
-
8/9/2019 PresentationJDBC_DAIICT
37/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 3 DriversJDBC-Middleware Pure Java Driver
JDBC driver translates JDBC calls into a DBMS-independent protocol
Then, communicates over a socket with a middleware
server that translates Java code into native API DBMScalls
No client code need be installed
Single driver provides access to multiple DBMSs, eg.
WebLogic Tengah drivers Type 3 drivers auto-download for applets.
-
8/9/2019 PresentationJDBC_DAIICT
38/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 4 DriversPure Java Drivers
Java drivers talk directoy to the DBMSusing Java sockets
No Middleware layer needed, access isdirect.
Simplest solution available.
No client code need be installed. Example: JConnect for Sybase
Type 4 drivers auto-download for applets
-
8/9/2019 PresentationJDBC_DAIICT
39/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Result Sets and Cursors
Result Sets are returned from queries.
Number of rows in a RS can be zero, one,
or more Cursors are iterators that iterate through
a result set
JDBC 2.0 allows for backward as well asforward cursors, including the ability togo to a specific row or a relative row
-
8/9/2019 PresentationJDBC_DAIICT
40/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
A JDBC Primer
First, load the JDBC Driver:
call new to load the drivers implementation of Driver class(redundant--Class.forName does this for you automatically) and callDriverManager.RegisterDriver()
add driver to the jdbc.drivers property - DriverManager will load
these automatically eg: ~/.hotjava/properties:
jdbc.drivers=com.oracle.jdbc.OracleDriver:etc;
or programatically:
String old = sysProps.getProperty(jdbc.drivers);
drivers.append(: + oldDrivers); sysProps.put(jdbc.drivers, drivers.toString());
call Class.forName and pass it the classname for the driverimplementation
-
8/9/2019 PresentationJDBC_DAIICT
41/127
-
8/9/2019 PresentationJDBC_DAIICT
42/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
SQL Statements
Create some form of Statement
Statement
Represents a basic SQL statement
Statement stmt = conn.createStatement();
PreparedStatement
A precompiled SQL statement, which can offer
improved performance, especially forlarge/complex SQL statements
Callable Statement
Allows JDBC programs access to stored
procedures
-
8/9/2019 PresentationJDBC_DAIICT
43/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Execute the Statement
executeQuery(): execute a query and get a ResultSet back
executeUpdate(): execute an update and get back an intspecifying number of rows acted on
UPDATE
DELETE execute(): execute unknown SQL and returns true if a resultSet
is available:
Statement genericStmt = conn.createStatement();
if( genericStmt.execute(SQLString)) {
ResultSet rs = genericStmt.getResultSet(); process(); } else {
int updated = genericStmt.getUpdateCount();processCount();
}
etc.
-
8/9/2019 PresentationJDBC_DAIICT
44/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Result Sets
ResultSet rs = stmt.executeQuery(select id, price frominventory);
rs.next() - go to next row in ResultSet
call once to access first row: while(rs.next()) {}
getXXX(columnName/indexVal) getFloat()
getInt()
getDouble()
getString() (highly versatile, inclusive of others;
automatic conversion to String for most types) getObject() (returns a generic Java Object)
rs.wasNull() - returns true if last get was Null
-
8/9/2019 PresentationJDBC_DAIICT
45/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Prepared Statements
Use for complex queries or repeated queries
Features:
precompiled at database (statement usually sent todatabase immediately on creation for compilation)
supply with new variables each time you call it (repeatedlyeg.)
eg:
PreparedStatement ps = conn.prepareStatement(updatetable set sales = ? Where custName = ?);
Set with values (use setXXX() methods on PreparedStatement: ps.setInt(1, 400000);
ps.setString(2, United Airlines);
Then execute:
int count = ps.executeUpdate();
U i h JDBC M D
-
8/9/2019 PresentationJDBC_DAIICT
46/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using the JDBC MetaDataInterface
ResultSet: ResultSetMetaData getMetaData()
ResultSetMetaData provides information about the types andproperties of the DDL properties of a ResultSet object
ResultSetMetaData provides various methods for finding out
information about the structure of a ResultSet: getColumnClassName(int col): gets fully-qualified Java class name
to which a column value will be mapped; eg. Java.lang.Integer,etc.
getColumnCount(): gets the number of columns in the ResultSet
getColumnDisplaySize(int col): gets the normal maximum width in
characters for column getColumnName(int col): gets the name of column
int getColumnType(int col): gets the JDBC type (java.sql.Types) forthe value stored in col; eg. Value 12 = JDBC VARCHAR, etc.
getPrecision(int col): for numbers, gets the mantissa length, for
others, gets the number of bytes for column
-
8/9/2019 PresentationJDBC_DAIICT
47/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC Transactions
A Transactions ACID properties are:
Atomic: The entire set of actions must succeed or the set fails
Consistent: consistent state transfer from one state to thenext
Isolated: A transaction is encapsulated and unmodifiable untilthe execution of the transaction set is complete
Durable: Changes committed through a transaction surviveand tolerate system failures.
Classic Example 1: Bank Transfer from one account to another
Step 1: withdrawal from Account A
Step 2: deposit into Account B
-
8/9/2019 PresentationJDBC_DAIICT
48/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using Transactions
Step 1: turn off autocommit:
conn.setAutoCommit(false);
Step 2: create and execute statements like normal
Step 3: fish or cut bait: commit or rollback
if all succeeded:
conn.commit();
else, if one or more failed:
conn.rollback();
Step 4 (Optional): turn autocommit back on: conn.setAutoCommit(true);
-
8/9/2019 PresentationJDBC_DAIICT
49/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Rolling Back Transactions
When you get a SQLException, you are not told what part of thetransaction succeeded and what part failed (this should beirrelevant)
Best Practice:
try to rollback() (may throw new SQLException) start over
Example:
catch( SQLException e) {
try {
conn.rollback();
} catch (SQLException e) { checkPlease(); }
}
T ti d P f
-
8/9/2019 PresentationJDBC_DAIICT
50/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Transactions and PerformanceImplications
Favor Transactions:
Disabling auto-commit means fewer commits over the wire(from driver to DBMS) which may cut down on IO overheadat the dataserver
Favor Autocommit: enabling autocommit may improve performance when
multiple users are vying for database resources becauselocks are held for shorter periods of time
locks are only held per transaction. In autocommit mode, eachstatement is essentially a transaction
locks may be either page-level or row-level locks, the latterbeing more efficient (Oracle)
-
8/9/2019 PresentationJDBC_DAIICT
51/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Transaction Isolation Modes
TRANSACTION_NONE
Transactions are disabled or unsupported
TRANSACTION_READ_UNCOMMITTED
Open policy that allows others to read uncommitted segments of atransaction, high potential for dirty reads
TRANSACTION_READ_COMMITTED
Closed policy that disallows others reading uncommitted segments.They must block until a commit is received, dirty reads areforbidden.
TRANSACTION_REPEATABLE_READ
subsequent read transactions always get same set regardless ofalteration until they call commit(), after which they get thechanged data
TRANSACTION_SERIALIZABLE
as above but also adds row insertion protection as well. If atransaction reads, and another transaction adds a row, and the first
transaction reads again, it will get the original set without seeing
-
8/9/2019 PresentationJDBC_DAIICT
52/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Stored Procedures
A Stored Procedure is written in a metalanguage defined by theDBMS vendor
Used to batch or group multiple SQL statements that are stored inexecutable form at the database
Written in some internal programming language of the DBMS: Oracles PL/SQL
Sybases Transact-SQL
THESE LANGUAGES ARE NON-PORTABLE from one DBMS toanother (with the exception of the SQLJ standard, which allows
you to write SQL in standard Java and have that understood byany DBMS that supports the SQLJ standard).
-
8/9/2019 PresentationJDBC_DAIICT
53/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Incompatibilities
Oracle Example:
CREATE PROCEDURE sp_select_min_bal@balance IN FLOAT,
ASSELECT account_idWHERE balance > @balance
Sybase Example:
create proc sp_select_min_bal(@balance real)
asselect account_idwhere balance > @balancereturn
-
8/9/2019 PresentationJDBC_DAIICT
54/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Why Use Stored Procedures?
Faster Execution of SQL (compiled and in-memorystored query plan)
Reduced Network Traffic
Modular Programming Automation of complex or sensitive transactions
Syntax checking at time of creation of SP
Syntax supports if, else, while loops, goto, local
variables, etc., all of which dynamic SQL doesnt have
-
8/9/2019 PresentationJDBC_DAIICT
55/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using Stored Procedures
Create a CallableStatement (using prepareCall which is similar toprepareStatement)
CallableStatement stmt =
conn.prepareCall({call sp_setBalance(?,?)}
stmt.registerOutParameter(2, Types.FLOAT); stmt.setInt(1, custID);
stmt.setFloat(2, 213432.625);
stmt.execute();
Float newBalance = stmt.getFloat(2);
Always register OUT or INOUT parameters in storedprocedures using registerOutParameter()
-
8/9/2019 PresentationJDBC_DAIICT
56/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
How-to start
Register and instantiate the driver
jdbc.driver property (from command line)
Java Djdbc.drivers=org.postgresql.Driverexample
Hardcoded
Class.forName( org.postgresql.Driver );
This allow runtime loading of a specific driver !
Tricky
New org.postgresql.Driver
-
8/9/2019 PresentationJDBC_DAIICT
57/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Connecting
Connecting to a DB
Db=DriverManager.getConnection(url, usr,pwd);
No DB specification (the driver has been loadedand will be selected by the DriverManagerregarding url).
URL syntax:
Jdbc:postgresql:database
Jdbc:postgresql://host/dabase
Jdbc:postgresql://host:port/dabase
Jdbc:postgresql:database?user=me
Jdbc:postgresql:database?user=me&password=mypass
-
8/9/2019 PresentationJDBC_DAIICT
58/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Connection methods
setAutoCommit();
Transaction mode
Rollback(); Commit();
PreparedStatement
CreateStatement
-
8/9/2019 PresentationJDBC_DAIICT
59/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Doing a statement
St = db.createStatement();
St.executeUpdate( sql code );
St.executeQuery( sql code ); St.execute( sql code );
St.addBatch( sql statement );
St.executeBatch();
Etc.
-
8/9/2019 PresentationJDBC_DAIICT
60/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Resultset
Result=executeUpdate( select * fromtoto);
Result.getMetaData(); Retrieves the number, types and properties of this
ResultSet object's columns
Result.next()
Moves the cursor down one row from its currentposition
Result.getObject(i) Gets the value of the designated column in the current
row of this ResultSet object as an Object in the Java
programming language
-
8/9/2019 PresentationJDBC_DAIICT
61/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Example
import java.sql.* ; public Connection conn = DriverManager.getConnection(url class ShowStudents { public static void main(String args[]) throws Exception { String url = jdbc:mysql://localhost/opennet_fall01 ; System.setProperty(jdbc.drivers, org.gjt.mm.mysql.Driver) ;
) ; Statement stat = conn.createStatement() ; ResultSet rs = stat.executeQuery(SELECT * FROM students) ; while(rs.next()) System.out.println(rs.getString(1) + + rs.getString(2) + + rs.getString(3)) ; conn.close() ;
} }
-
8/9/2019 PresentationJDBC_DAIICT
62/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
importjava.sql.* ;public Connection conn =
DriverManager.getConnection(url class ShowStudents {
public static void main(String args[]) throws Exception {
String url = jdbc:mysql://localhost/opennet_fall01 ;
System.setProperty(jdbc.drivers,org.gjt.mm.mysql.Driver) ;
) ;
Statement stat = conn.createStatement() ;
ResultSet rs = stat.executeQuery(SELECT * FROM students) ;
while(rs.next())System.out.println(rs.getString(1) + +
rs.getString(2) + + rs.getString(3)) ;
conn.close() ;}
}
-
8/9/2019 PresentationJDBC_DAIICT
63/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Generally speaking the syntax of the URL should followthe normal conventions for Internet URLs:
protocol // host: port/ name
protocolwill be a sub-protocol ofjdbc:, e.g.
jdbc:mysql: hostand portare self-explanatory.
name is the name of the database on the host.
The precise format depends on the driver. Oracle JDBCURLs follow the general pattern, but they use differentseparators. @ and : in place of// and/.
-
8/9/2019 PresentationJDBC_DAIICT
64/127
Data Entry Forms
-
8/9/2019 PresentationJDBC_DAIICT
65/127
Java Database Connectivity (JDBC)
-
8/9/2019 PresentationJDBC_DAIICT
66/127
import java.sql.*;
class JdbcTest {
public static void main (String args []) throws SQLException {
// Load Oracle driver
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
// Connect to the local database
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myhost:1521:ORCL","scott", "tiger");
JDBC
-
8/9/2019 PresentationJDBC_DAIICT
67/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
// Query the student names
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT name FROM Student");
// Print the name out
//name is the 2nd attribute of Student
while (rset.next ())
System.out.println (rset.getString (2));
//close the result set, statement, and the connection
rset.close();stmt.close();
conn.close();
-
8/9/2019 PresentationJDBC_DAIICT
68/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
PreparedStatement ObjectIfyou want to execute a Statement object many times, it will normallyreduce
execution time to use a PreparedStatement object instead.
PreparedStatement updateStud = conn.prepareStatement( "UPDATE
Student SET name = ? WHERE lastname LIKE ?");
updateStud.setString(1,John);
updateStud.setString(2,Smith);
updateStud.executeUpdate();
-
8/9/2019 PresentationJDBC_DAIICT
69/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
PreparedStatement Object
the following two code fragments accomplish the same thing:
Code Fragment 1:
String updateString = "UPDATE COFFEES SET SALES = 75 " +
"WHERE COF_NAME LIKE 'Colombian'";
stmt.executeUpdate(updateString);
Code Fragment 2:
PreparedStatement updateSales = con.prepareStatement( "UPDATE
COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian"); updateSales.executeUpdate():
-
8/9/2019 PresentationJDBC_DAIICT
70/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
int getInt(int columnIndex)
Retrieves the value of the designated column in the currentrow of this ResultSet object as an int in the Java programming
language.
int getInt(Str
ing columnName)
String getString(int columnIndex)
String getString(String columnName)
-
8/9/2019 PresentationJDBC_DAIICT
71/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using TransactionsWhen a connection is created, it is in auto-commit mode. This means that each
individual SQL statement is treated as a transaction and will beautomatically committed right after it is executed.
conn.setAutoCommit(false);....
transaction
...
con.commit();
con.setAutoCommit(true);
-
8/9/2019 PresentationJDBC_DAIICT
72/127
-
8/9/2019 PresentationJDBC_DAIICT
73/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Retrieving Exceptions
JDBC lets you see the warnings and exceptions generated by your DBMS andby the Java compiler. To see exceptions, you can have a catch block print
them out. For example, the following two catch blocks from the sample codeprint out a message explaining the exception:
try {// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.} catch(SQLException ex) {System.err.println("SQLException: " + ex.getMessage());
}
JSP S
-
8/9/2019 PresentationJDBC_DAIICT
74/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JSPSyntax
Comment
Expression
Scriplet
Include
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
75/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
76/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
Data Entry Menu
Courses
Classes
Students
Menu HTML Code
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
77/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
Open connection code
Statement code
Presentation code
Close connection code
JSP Code
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
78/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
Open Connectivity Code
-
8/9/2019 PresentationJDBC_DAIICT
79/127
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
80/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
SSN
First
Last
College
Iteration Code
Presentation Code
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
81/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
E t F Fi t Att t
-
8/9/2019 PresentationJDBC_DAIICT
82/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
Iteration Code
Entr Form First Attempt
-
8/9/2019 PresentationJDBC_DAIICT
83/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
Close Connectivity Code
Entry Form Second Attempt
-
8/9/2019 PresentationJDBC_DAIICT
84/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Entry Form Second Attempt
-
8/9/2019 PresentationJDBC_DAIICT
85/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
JSPCode
Entry Form Second Attempt
-
8/9/2019 PresentationJDBC_DAIICT
86/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
// Check if an insertion isrequestedStringaction = request.getParameter("action");
if (action != null && action.equals("insert")) {
conn.setAutoCommit(false);
// Create the prepared statementand use itto// INSERTthe studentattrs INTO the Studenttable.
PreparedStatementpstmt = conn.prepareStatement(
("INSERT INTO Student VALUES(?, ?, ?, ?, ?)"));
pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN")));
pstmt.setString(2, request.getParameter("ID"));
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
Insertion Code
Entry Form Second Attempt
-
8/9/2019 PresentationJDBC_DAIICT
87/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
SSN
First
Last
College
Insert Form Code
Iteration Code
Presentation Code
Entry Form Second Attempt
-
8/9/2019 PresentationJDBC_DAIICT
88/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Insert Form Code
Entry Form Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
89/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Entry Form Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
90/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Open connection codeInsertion Code
Update Code
Delete Code
Statement code
Presentation code
Close connection code
JSP Code
Entry Form Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
91/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
// Check if an update isrequestedif (action != null && action.equals("update")) {
conn.setAutoCommit(false);
// Create the prepared statementand use itto
// UPDATE the studentattributes in the Studenttable.PreparedStatementpstatement = conn.prepareStatement(
"UPDATE StudentSET ID = ?, FIRSTNAME = ?, " +
"LASTNAME = ?, COLLEGE = ? WHERE SSN = ?");
pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));
introwCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Update Code
Entry Form Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
92/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
// Check if a delete isrequestedif (action != null && action.equals("delete")) {
conn.setAutoCommit(false);
// Create the prepared statementand use itto
// DELETE the student FROM the Studenttable.
PreparedStatementpstmt = conn.prepareStatement(
"DELETE FROM Student WHERE SSN = ?");
pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));introwCount = pstmt.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Delete Code
Entry Form - Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
93/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
SSN
First
Last
College
Insert Form Code
Iteration Code
Presentation Code
Entry Form - Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
94/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Iteration Code
Entry Form - Third Attempt
-
8/9/2019 PresentationJDBC_DAIICT
95/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
JDBC
-
8/9/2019 PresentationJDBC_DAIICT
96/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC
JDBC Road Map http://technet.oracle.com/tech/java/jroadmap/index2.htm? Info&jdbc/listing.htm SQLJ & JDBC Basic Samples http://technet.oracle.com/tech/java/sqlj_jdbc/index2.htm? Code&files/basic/basic.htm JDBC Drivers http://technet.oracle.com/software/tech/java/sqlj_jdbc/ htdocs/listing.htm Requires free registration
Certification http://technet.oracle.com/training/certification/
JDBC
-
8/9/2019 PresentationJDBC_DAIICT
97/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC
Suns JDBC Site
http://java.sun.com/products/jdbc/
JDBC Tutorial
http://java.sun.com/docs/books/tutorial/jdbc/
List of Available JDBC Drivers
http://industry.java.sun.com/products/jdbc/drivers/
API for java.sql
http://java.sun.com/j2se/1.4/docs/api/java/sql/
package-summary.html
-
8/9/2019 PresentationJDBC_DAIICT
98/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Seven Basic Steps in Using JDBC
1. Load the driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection
JDBC
-
8/9/2019 PresentationJDBC_DAIICT
99/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
JDBC
String username = "jay_debesee"; String password = "secret"; Connection connection = DriverManager.getConnection(oracleURL, username, password); Optionally, look up information about the database DatabaseMetaData dbMetaData = connection.getMetaData(); String productName =
dbMetaData.getDatabaseProductName(); System.out.println("Database: " + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); System.out.println("Version: " + productVersion);
Using MetaData
-
8/9/2019 PresentationJDBC_DAIICT
100/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
g
System-wide data
connection.getMetaData().getDatabaseProductName()
connection.getMetaData().getDatabaseProductVersion() Table-specific data
resultSet.getMetaData().getColumnCount()
When using the result, remember that
the index starts at 1, not 0 resultSet.getMetaData().getColumnName()
Using MetaData
-
8/9/2019 PresentationJDBC_DAIICT
101/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using MetaData
public class NorthwindServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(docType + );
String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String url = "jdbc:odbc:Northwind"; String username = ""; String password = ""; String tableName = request.getParameter("tableName"); if ((tableName == null) || (tableName.equals(""))) { tableName = "employees"; } showTable(driver, url, username, password, tableName, out); out.println(""); }
Using MetaData
-
8/9/2019 PresentationJDBC_DAIICT
102/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using MetaData
private void showTable(String driver, String url, String username, String password, String tableName, PrintWriter out) { try { Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password); DatabaseMetaData dbMetaData = connection.getMetaData(); out.println(""); String productName = dbMetaData.getDatabaseProductName(); out.println(" Database: " + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); out.println(" Version: " + productVersion + "\n");
Using MetaData
-
8/9/2019 PresentationJDBC_DAIICT
103/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using MetaData
Statement statement = connection.createStatement(); String query = "SELECT * FROM " + tableName; ResultSet resultSet = statement.executeQuery(query); out.println(""); ResultSetMetaData resultsMetaData = resultSet.getMetaData(); int columnCount = resultsMetaData.getColumnCount();
out.println(""); for(int i=1; i
-
8/9/2019 PresentationJDBC_DAIICT
104/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
import java.sql.*; public class UpdateCar { public static void UpdateCarNum(int carNo, int empNo) throws SQLException { Connection con = null; PreparedStatement pstmt = null; try { con = DriverManager.getConnection("jdbc:default:connection"); pstmt = con.prepareStatement( "UPDATE EMPLOYEES SET CAR_NUMBER
= ? " + "WHERE EMPLOYEE_NUMBER = ?"); pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo); pstmt.executeUpdate(); } finally { if (pstmt != null) pstmt.close(); } } }
Using MetaData
-
8/9/2019 PresentationJDBC_DAIICT
105/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using MetaData
Overview
Through the Statement object, SQL statements are
sent to the database.
Three types of statement objects are available:
Statement
For executing a simple SQL statement
PreparedStatement
For executing a precompiled SQL statement passing
in parameters CallableStatement
For executing a database stored procedure
Useful Statement Methods
-
8/9/2019 PresentationJDBC_DAIICT
106/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
executeQuery Executes the SQL query and returns the data in a table (ResultSet) The resulting table may be empty but never null ResultSet results = statement.executeQuery("SELECT a, b FROM table"); executeUpdate Used to execute for INSERT, UPDATE, or DELETE SQL statements The return is the number of rows that were affected in the database
Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE and ALTER TABLE int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" + "WHERE STATUS=0");
Useful Statement Methods
-
8/9/2019 PresentationJDBC_DAIICT
107/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Useful Statement Methods
execute Generic method for executing stored procedures and prepared statements Rarely used (for multiple return result sets) The statement execution may or may not return a
ResultSet (use statement.getResultSet). If the return value is true, two or more result sets were produced getMaxRows/setMaxRows Determines the maximum number of rows a ResultSet may contain Unless explicitly set, the number of rows is unlimited (return value of 0) getQueryTimeout/setQueryTimeout Specifies the amount of a time a driver will wait for a STATEMENT to complete before throwing a SQLException
Useful Statement Methods
-
8/9/2019 PresentationJDBC_DAIICT
108/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Useful Statement Methods
Idea If you are going to execute similar SQL statements multiple times, using prepared (parameterized) statements can be more efficient Create a statement in standard form that is sent to the database for compilation before actually being used Each time you use it, you simply replace some of the marked parameters using the setXxx methods As PreparedStatement inherits from Statement the corresponding execute methods have no
parameters execute() executeQuery() executeUpdate()
Useful Statement Methods
-
8/9/2019 PresentationJDBC_DAIICT
109/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Useful Statement Methods
Connection connection = DriverManager.getConnection(url, user, password); PreparedStatement statement = connection.prepareStatement("UPDATE employees "+ "SET salary = ? " + "WHERE id = ?"); int[] newSalaries = getSalaries(); int[] employeeIDs = getIDs(); for(int i=0; i
-
8/9/2019 PresentationJDBC_DAIICT
110/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Idea
By default, after each SQL statement is executed the
changes are automatically committed to the database
Turn auto-commit off to group two or morestatements
together into a transaction
connection.setAutoCommit(false)
Call commit to permanently record the changes to the
database after executing a group of statements Call rollback if an error occurs
Transactions
-
8/9/2019 PresentationJDBC_DAIICT
111/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Transactions: Example Connection connection = DriverManager.getConnection(url, username, passwd); connection.setAutoCommit(false); try { statement.executeUpdate(...); statement.executeUpdate(...);
connection.commit(); } catch (Exception e) { try { connection.rollback(); } catch (SQLException sqle) { // report problem } } finally {
try { connection.close(); } catch (SQLException sqle) { } }
Useful Connection Methods
-
8/9/2019 PresentationJDBC_DAIICT
112/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Useful Connection Methods
(for Transactions) getAutoCommit/setAutoCommit By default, a connection is set to auto-commit Retrieves or sets the auto-commit mode commit Force all changes since the last call to commit to become permanent Any database locks currently held by this Connection object are released
rollback Drops all changes since the previous call to commit Releases any database locks held by this Connection object
createProcedure
-
8/9/2019 PresentationJDBC_DAIICT
113/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
createProcedure
String createProcedure = "create procedureSHOW_SUPPLIERS " + "as " + "selectSUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "fromSUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID =COFFEES.SUP_ID " + "order by SUP_NAME"; The following
code fragment uses the Connection object con to create aStatement object, which is used to send the SQL statementcreating the stored procedure to the database:
Statement stmt = con.createStatement();stmt.executeUpdate(createProcedure);
Useful Statement Methods
-
8/9/2019 PresentationJDBC_DAIICT
114/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Useful Statement Methods
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
-
8/9/2019 PresentationJDBC_DAIICT
115/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Type Differences
-
8/9/2019 PresentationJDBC_DAIICT
116/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Type Differences
SQLServer OracleINTEGER NUMBER(10)
SMALLINT NUMBER(6)
TINYINT NUMBER(3)
REAL FLOAT
FLOAT FLOAT
BIT NUMBER(1)
VARCHAR(n) VARCHAR2(n)
TEXT CLOBIMAGE BLOB
BINARY(n) RAW(n) or BLOB
-
8/9/2019 PresentationJDBC_DAIICT
117/127
Data Type Differences
-
8/9/2019 PresentationJDBC_DAIICT
118/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Type Differences
SQL
ServerO
racleVARBINARY RAW(n) or BLOB
DATETIME DATE
SMALL-DATETIME DATE
MONEY NUMBER(19,4)
NCHAR(n) CHAR(n*2)
NVARCHAR(n) VARCHAR(n*2)
SMALLMONEY NUMBER(10,4)
TIMESTAMP NUMBER
SYSNAME VARCHAR2(30),
VARCHAR2(128)
-
8/9/2019 PresentationJDBC_DAIICT
119/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Time
-
8/9/2019 PresentationJDBC_DAIICT
120/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Time
SQL Server
Datetime: 1/300th second
OracleDate: 1 second
Timestamp: 1/100 millionth second
-
8/9/2019 PresentationJDBC_DAIICT
121/127
Some Imp Reflections
-
8/9/2019 PresentationJDBC_DAIICT
122/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Some Imp Reflections
The difference between Varchar and Varchar2 is bothare variable length but only 2000 bytes of character ofdata can be store in varchar where as 4000 bytes ofcharacter of data can be store in varchar2.
VARCHAR2(size)Variable length character string havingmaximum length size bytes.
NVARCHAR2(size)Variable length national character setstring having maximum length size bytes.You must specify size
Comparisions of Oracle Datatype
-
8/9/2019 PresentationJDBC_DAIICT
123/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Comparisions ofOracle Datatype
http://www.ss64.com/orasyntax/datatypes.html
-
8/9/2019 PresentationJDBC_DAIICT
124/127
Why use LOBs and not LONG or LONG RAW: -
-
8/9/2019 PresentationJDBC_DAIICT
125/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
LOBs offer more features to the developer than a LONG or LONGRAW. The main differences between the data types also indicatewhy you would use a LOB instead of a LONG or LONG RAW. Thesedifferences include the following: -
You can have more than one LOB column in a table, whereas youare restricted to just one LONG or LONG RAW column per table.
When you insert into a LOB, the actual value of the LOB is storedin a separate segment (except for in-line LOBs) and only the LOBlocator is stored in the row, thus making it more efficient from astorage as well as query perspective. With LONG or LONG RAW,the entire data is stored in-line with the rest of the table row.
Why use LOBs and not LONG or LONG RAW: -
-
8/9/2019 PresentationJDBC_DAIICT
126/127
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
LOBs allow a random access to its data,whereas with a LONG you have to go in for asequential read of the data from beginning to
end. The maximum length of a LOB is 4 Gig as
compared to a 2 Gig limit on LONG
Querying a LOB column returns the LOB locator
and not the entire value of the LOB. On theother hand, querying LONG returns the entirevalue contained within the LONG column.
LOB
-
8/9/2019 PresentationJDBC_DAIICT
127/127
CLOB A Character LOB. Used to store character data.
BLOB A Binary LOB. Used to store binary, raw data
NCLOB A LOB that stores character data thatcorresponds to the national character set defined forthe database.
I The only external LOB data type in Oracle 8i is called
a BFILE.
BFILE - Short for Binary File. These hold references tolarge binary data stored as physical files in the OSoutside the database.