0% found this document useful (0 votes)
92 views

Wel Come: Dhiraj Thakkar (

D1: The document discusses JDBC and provides an overview of key concepts like database architectures, SQL, JDBC drivers and architecture, and the standard query language SQL. D2: It also includes code examples for a simple "Hello World" Java program and explanations of concepts like the main method signature and how output is printed. D3: The document is intended as teaching material, as it is authored by Dhiraj Thakkar and contains a course map and descriptions of tools needed for the course.

Uploaded by

mattdmn
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Wel Come: Dhiraj Thakkar (

D1: The document discusses JDBC and provides an overview of key concepts like database architectures, SQL, JDBC drivers and architecture, and the standard query language SQL. D2: It also includes code examples for a simple "Hello World" Java program and explanations of concepts like the main method signature and how output is printed. D3: The document is intended as teaching material, as it is authored by Dhiraj Thakkar and contains a course map and descriptions of tools needed for the course.

Uploaded by

mattdmn
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 127

Wel Come

Dhiraj Thakkar (MD, Royal Technosoft)

RTIM-Merchant Navy,MS-IT,J2EE Application 3 years


1 Year Webpshere Portal Server
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

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 emp


table.

• Java example to Insert employee record into emp table.


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 and
displaying them. (Need not to cover installation of Tomcat etc.)
• Connection Pooling

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)

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
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”);
}
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Hello World: Java and C

S1: // HelloWorld.java: Hello World program /* helloworld.c: Hello World program */


S2: import java.lang.*;
#define <stdio.h>
S3: class HelloWorld
{
void main(int argc, char *argv[])
S4: public static void main(String args[])
{ {
S6: System.out.println(“Hello World”); printf(“Hello World\n”);
} }
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Program Processing

 Compilation
# javac HelloWorld.java
results in HelloWorld.class

 Execution
# java HelloWorld
Hello World

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


public static void main(String args[])
 public: The keyword “public” is an access
specifier that declares the main method as
unprotected.
 static: It says this method belongs to the entire
class and NOT a part of any objects of class.
The main must always be declared static since
the interpreter users this before any objects are
created.
 void: The type modifier that states that main
does not return any value.

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 out
which is an instance of the java.io.PrintStream
class. So when we write System.out.println(),
we are really invoking the println() method of
the “out” field of the java.lang.System class.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Program Structure
Documentation Section

Package Statement

Import Statements

Interface Statements

Class Declarations

Main Method Class


{
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Database Architectures

 Two-tier
 Three-tier
 N-tier

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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Three-Tier Architecture

 Application Server sits between client


and database

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Three-Tier Pros

 flexible: can change one part without


affecting others
 can connect to different databases
without changing code
 specialization: presentation / business
logic / data management
 can cache queries
 can implement proxies and firewalls

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Three-Tier Cons

 higher complexity
 higher maintenance
 lower network efficiency
 more parts to configure (and buy)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Three-Tier Pros

 flexible: can change one part without


affecting others
 can connect to different databases
without changing code
 specialization: presentation / business
logic / data management
 can cache queries
 can implement proxies and firewalls

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


N-Tier Architecture

 Design your application using as many


“tiers” as you need
 Use Object-Oriented Design techniques
 Put the various components on whatever
host makes sense
 Java allows N-Tier Architecture, especially
with RMI and JDBC

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

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 multiple
functionality

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC Ancestry

X/OPEN

ODBC JDBC

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 than one
database
 Ideal: can change database engines without
changing any application code

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC Drivers

 Type I: “Bridge”
 Type II: “Native”
 Type III: “Middleware”
 Type IV: “Pure”

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Overall Architecture

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Introducing JDBC

 According to Sun, JDBC is not an


acronym, but is commonly misinterpreted
to mean Java DataBase Connectivity
 Supports ANSI SQL 92 Entry Level

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
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 where id >
1003

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Data Definition Language

 CREATE DATABASE - allows you to create


a database
 CREATE TABLE - allows you to create a
table definition in a database
 DROP TABLE - removes a table from a
database
 ALTER TABLE - modifies the definition of
a table in a database

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC Framework

 The JDBC driver manager


 The JDBC driver

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


The JDBC Driver Manager
 Management layer of JDBC, interfaces between the
client and the driver.
 Keeps a hash list of available drivers
 Manages driver login time limits and printing of log
and tracing messages
 Secure because manager will only allow drivers that
come from local file system or the same initial class
loader requesting a connection
 Most popular function:
 Connection getConnection(url, id, passwd);

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC Driver Types

 Type 1 (JDBC-ODBC Bridge Technology)


 Type 2 (JNI drivers for C/C++ connection
libraries)
 Type 3 (Socket-level Middleware
Translator)
 Type 4 (Pure Java-DBMS driver)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC Drivers (Fig.)

Type I ODBC
ODBC
“Bridge” Driver

Type II
JDBC CLI (.lib)
“Native”

Type III Middleware


“Middleware” Server

Type IV
“Pure”
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 1 Drivers
JDBC-ODBC Bridges
 JDBC driver translates call into ODBC and
redirects ODBC call to an ODBC driver on
the DBMS
 ODBC binary code must exist on every
client
 Translation layer compromises execution
speed to small degree

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Type 1 Drivers
JDBC-ODBC Bridges
 The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls
into ODBC (Open DataBase Connectivity) calls and sends them
to the ODBC driver. As such, the ODBC driver, as well as, in
many cases, the client database code, must be present on the
client machine. Figure 1 shows a typical JDBC-ODBC Bridge
environment.

 Diagram

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Type 2 Drivers
Native-API + Java Driver
 Java driver makes JNI calls on the client API (usually
written 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Type 3 Drivers
JDBC-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 DBMS
calls
 No client code need be installed
 Single driver provides access to multiple DBMSs, eg.
WebLogic Tengah drivers
 Type 3 drivers auto-download for applets.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Type 4 Drivers
Pure Java Drivers
 Java drivers talk directoy to the DBMS
using Java sockets
 No Middleware layer needed, access is
direct.
 Simplest solution available.
 No client code need be installed.
 Example: JConnect for Sybase
 Type 4 drivers auto-download for applets

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 as
forward cursors, including the ability to
go to a specific row or a relative row

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


A JDBC Primer
 First, load the JDBC Driver:
 call new to load the driver’s implementation of Driver class
(redundant--Class.forName does this for you automatically) and call
DriverManager.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 driver


implementation

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Create a Connection to the
database vi the driver
 Call the getConnection method on the DriverManager
object.
 Connection conn = DriverManager.getConnection(url,
login, password)
 url: jdbc:subprotocol:host:port[/database]
 registered subprotocol: sybase, odbc, msql, etc.

 eg: jdbc:sybase:Tds:limousin:4100/myDB

 Only requirement: The relevant Drivers must be able to


recognize their own URL

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 for large/complex
SQL statements
 Callable Statement
 Allows JDBC programs access to stored procedures

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 int specifying 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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Result Sets
 ResultSet rs = stmt.executeQuery(“select id, price from
inventory”);
 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Prepared Statements
 Use for complex queries or repeated queries
 Features:
 precompiled at database (statement usually sent to database

immediately on creation for compilation)


 supply with new variables each time you call it (repeatedly eg.)

 eg:
 PreparedStatement ps = conn.prepareStatement(“update table

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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Using the JDBC MetaData
Interface
 ResultSet: ResultSetMetaData getMetaData()
 ResultSetMetaData provides information about the types and
properties 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) for
the 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC Transactions
 A Transaction’s ACID properties are:
 Atomic: The entire set of actions must succeed or the set fails

 Consistent: consistent state transfer from one state to the

next
 Isolated: A transaction is encapsulated and unmodifiable until

the execution of the transaction set is complete


 Durable: Changes committed through a transaction survive

and 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

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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Rolling Back Transactions
 When you get a SQLException, you are not told what part of the
transaction succeeded and what part failed (this should be
irrelevant)
 Best Practice:
 try to rollback() (may throw new SQLException)

 start over

 Example:
 catch( SQLException e) {
 try {
 conn.rollback();
 } catch (SQLException e) { checkPlease(); }
 }

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Transactions and Performance
Implications
 Favor Transactions:
 Disabling auto-commit means fewer commits over the wire

(from driver to DBMS) which may cut down on IO overhead


at the dataserver
 Favor Autocommit:
 enabling autocommit may improve performance when

multiple users are vying for database resources because


locks are held for shorter periods of time
 locks are only held per transaction. In autocommit mode, each
statement is essentially a transaction
 locks may be either page-level or row-level locks, the latter
being more efficient (Oracle)

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 a
transaction, 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 are forbidden.
 TRANSACTION_REPEATABLE_READ
 subsequent read transactions always get same set regardless of
alteration until they call commit(), after which they get the changed
data
 TRANSACTION_SERIALIZABLE
 as above but also adds row insertion protection as well. If a transaction
reads, and another transaction adds a row, and the first transaction
reads again, it will get the original set without seeing the new row.
 Conn.setTransactionIsolation(TRANSACTION_READ_COMMITTED)
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Stored Procedures
 A Stored Procedure is written in a metalanguage defined by the
DBMS vendor
 Used to batch or group multiple SQL statements that are stored in
executable form at the database
 Written in some internal programming language of the DBMS:
 Oracle’s PL/SQL

 Sybase’s Transact-SQL

 THESE LANGUAGES ARE NON-PORTABLE from one DBMS to


another (with the exception of the SQLJ standard, which allows
you to write SQL in standard Java and have that understood by
any DBMS that supports the SQLJ standard).

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Incompatibilities
 Oracle Example:
 CREATE PROCEDURE sp_select_min_bal
@balance IN FLOAT,
AS
SELECT account_id
WHERE balance > @balance

 Sybase Example:
 create proc sp_select_min_bal
(@balance real)
as
select account_id
where balance > @balance
return

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Why Use Stored Procedures?
 Faster Execution of SQL (compiled and in-memory
stored 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 doesn’t have

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Using Stored Procedures
 Create a CallableStatement (using prepareCall which is similar to
prepareStatement)
 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 stored
procedures using registerOutParameter()

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.Driver
example
 Hardcoded
 Class.forName(« org.postgresql.Driver »);
 This allow runtime loading of a specific driver !
 Tricky
 New org.postgresql.Driver

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 loaded and
will be selected by the DriverManager regarding 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Connection methods

 setAutoCommit();
 Transaction mode
 Rollback();
 Commit();
 PreparedStatement
 CreateStatement

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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Resultset

 Result=executeUpdate(« select * from toto»);


 Result.getMetaData();

Retrieves the number, types and properties of this ResultSet
object's columns
 Result.next()
 Moves the cursor down one row from its current
position
 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

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() ;
 }
 }

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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() ;
}
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
 Generally speaking the syntax of the URL should follow
the normal conventions for Internet URLs:
 protocol // host : port / name
 protocol will be a sub-protocol of jdbc:, e.g.
 jdbc:mysql:
 host and port are self-explanatory.
 name is the name of the database on the host.
 The precise format depends on the driver. Oracle JDBC
URLs follow the general pattern, but they use different
separators.
 @ and : in place of // and /.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Data Entry Forms
Java Database Connectivity (JDBC)
JDBC

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");
// 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();

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


PreparedStatement Object
If you want to execute a Statement object many times, it will normally reduce
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();

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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


  int getInt(int columnIndex)
          Retrieves the value of the designated column in the current row of this
ResultSet object as an int in the Java programming language.
  int getInt(String columnName)

  String getString(int columnIndex)
         
  String getString(String columnName)

        

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Using Transactions
When a connection is created, it is in auto-commit mode. This means that each
individual SQL statement is treated as a transaction and will be automatically
committed right after it is executed.

conn.setAutoCommit(false);
....
transaction
...
con.commit();
con.setAutoCommit(true);

        

        
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using Transactions
example

con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES
SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES
SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);     

        
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Retrieving Exceptions

JDBC lets you see the warnings and exceptions generated by your DBMS
and by 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
code print 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());
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JSP Syntax

 Comment
 <%-- Comment --%>
 Expression
 <%= java expression %>
 Scriplet
 <% java code fragment %>
 Include
 <jsp:include page="relativeURL" />

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt

Menu HTML Code


<b>Data Entry Menu</b>
<ul>
<li>
<a href="courses.jsp">Courses<a>
</li>
<li>
<a href="classes.jsp">Classes<a>
</li>
<li>
<a href="students.jsp">Students<a>
</li>
</ul>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
<jsp:include page="menu.html" />
</td>
<td>
Open connection code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt
Open Connectivity Code
<%-- Set the scripting language to java and --%>
<%-- import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>

<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());

// Make a connection to the Oracle datasource


Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@feast.ucsd.edu:1521:source",
“user", “pass");
%>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt
Statement Code
<%
// Create the statement
Statement statement = conn.createStatement();

// Use the statement to SELECT the student attributes


// FROM the Student table.
ResultSet rs = statement.executeQuery
("SELECT * FROM Student");
%>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>

<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt
Iteration Code
<tr>
<%-- Get the SSN, which is a number --%>
<td><%= rs.getInt("SSN") %></td>

<%-- Get the ID --%>


<td><%= rs.getString("ID") %></td>

<%-- Get the FIRSTNAME --%>


<td><%= rs.getString("FIRSTNAME") %></td>

<%-- Get the LASTNAME --%>


<td><%= rs.getString("LASTNAME") %></td>

<%-- Get the COLLEGE --%>


<td><%= rs.getString("COLLEGE") %></td>
</tr>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - First Attempt
Close Connectivity Code
<%
// Close the ResultSet
rs.close();

// Close the Statement


statement.close();

// Close the Connection


conn.close();

} catch (SQLException sqle) {


out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
%>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - Second Attempt

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - Second Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - Second Attempt
Insertion Code
// Check if an insertion is requested
String action = request.getParameter("action");
if (action != null && action.equals("insert")) {

conn.setAutoCommit(false);

// Create the prepared statement and use it to


// INSERT the student attrs INTO the Student table.
PreparedStatement pstmt = 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);
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Insert Form Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="insert" name="action">
<th><input value="" name="SSN" size="10"></th>
<th><input value="" name="ID" size="10"></th>
<th><input value="" name="FIRSTNAME" size="15"></th>
<th><input value="" name="LASTNAME" size="15"></th>
<th><input value="" name="COLLEGE" size="15"></th>
<th><input type="submit" value="Insert"></th>
</form>
</tr>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - Third Attempt

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - Third Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Update Code
Delete Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Update Code
// Check if an update is requested
if (action != null && action.equals("update")) {

conn.setAutoCommit(false);

// Create the prepared statement and use it to


// UPDATE the student attributes in the Student table.
PreparedStatement pstatement = conn.prepareStatement(
"UPDATE Student SET ID = ?, FIRSTNAME = ?, " +
"LASTNAME = ?, COLLEGE = ? WHERE SSN = ?");

pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));

int rowCount = pstatement.executeUpdate();

conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Delete Code
// Check if a delete is requested
if (action != null && action.equals("delete")) {

conn.setAutoCommit(false);

// Create the prepared statement and use it to


// DELETE the student FROM the Student table.
PreparedStatement pstmt = conn.prepareStatement(
"DELETE FROM Student WHERE SSN = ?");

pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));
int rowCount = pstmt.executeUpdate();

conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Iteration Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="update" name="action">
<td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td>
<td><input value="<%= rs.getString("ID") %>" name="ID"></td>

<td><input type="submit" value="Update"></td>
</form>
<form action="students2.jsp" method="get">
<input type="hidden" value="delete" name="action">
<input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN">
<td><input type="submit" value="Delete"></td>
</form>
</tr>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Entry Form - Third Attempt

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/

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


JDBC
 Sun’s 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

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

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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Using MetaData

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

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("</CENTER></BODY></HTML>");
 }

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("<UL>");
 String productName =
 dbMetaData.getDatabaseProductName();
 out.println(" <LI><B>Database:</B> " +
 productName);
 String productVersion =
 dbMetaData.getDatabaseProductVersion();
 out.println(" <LI><B>Version:</B> " +
 productVersion +
 "\n</UL>");

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("<TABLE BORDER=1>");
 ResultSetMetaData resultsMetaData =
 resultSet.getMetaData();
 int columnCount = resultsMetaData.getColumnCount();
 out.println("<TR>");
 for(int i=1; i<columnCount+1; i++) {
 out.print("<TH>" + resultsMetaData.getColumnName(i));
 }
 out.println();
 while(resultSet.next()) {
 out.println("<TR>");
 for(int i=1; i<columnCount+1; i++) {
 out.print("<TD>" + resultSet.getString(i));
 }
 out.println();
 }
 out.println("</TABLE>");

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();
 }}}
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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Useful Statement Methods

 • 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");
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

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

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<employeeIDs.length; i++) {
 statement.setInt(1, newSalaries[i]);
 statement.setInt(2, employeeIDs[i]);
 statement.executeUpdate();
 }

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Transactions

 • 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 more
statements
 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Transactions

 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) { }
 }

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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


createProcedure

 String createProcedure = "create procedure


SHOW_SUPPLIERS " + "as " + "select
SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from
SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID =
COFFEES.SUP_ID " + "order by SUP_NAME"; The following

 code fragment uses the Connection object con to create a


Statement object, which is used to send the SQL statement
creating the stored procedure to the database:

 Statement stmt = con.createStatement();


stmt.executeUpdate(createProcedure);

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Useful Statement Methods

 CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");

 ResultSet rs = cs.executeQuery();

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Type Differences
SQL Server Oracle
INTEGER NUMBER(10)
SMALLINT NUMBER(6)
TINYINT NUMBER(3)
REAL FLOAT
FLOAT FLOAT
BIT NUMBER(1)
VARCHAR(n) VARCHAR2(n)
TEXT CLOB
IMAGE BLOB
BINARY(n) RAW(n) or BLOB

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Data Type Differences
SQL ServerOracle
VARBINARY 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)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Time

SQL Server
Datetime: 1/300th second
Oracle
Date: 1 second
Timestamp: 1/100 millionth second

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Column Aliases

SQL Server
select a=deptid, b=deptname,c=empno
from dept;
Oracle
select deptid a, deptname b, empno c
from dept;

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Some Imp Reflections
 The difference between Varchar and Varchar2 is both
are variable length but only 2000 bytes of character of
data can be store in varchar where as 4000 bytes of
character of data can be store in varchar2.

 VARCHAR2(size)Variable length character string having


maximum length size bytes.

 NVARCHAR2(size)Variable length national character set


string having maximum length size bytes.
You must specify size

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Comparisions of Oracle Datatype

 http://www.ss64.com/orasyntax/datatype
s.html

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


What are LOBs: -

 A LOB is a Large Object. LOBs are use to store large,


unstructured data, such as video, audio, photo images etc. With a
LOB you can store up to 4 Gigabytes of data. They are similar to a
LONG or LONG RAW but differ from them in quite a few ways.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Why use LOBs and not LONG or LONG RAW: -

 LOBs offer more features to the developer than a LONG or LONG


RAW. The main differences between the data types also indicate
why you would use a LOB instead of a LONG or LONG RAW. These
differences include the following: -

 You can have more than one LOB column in a table, whereas you
are restricted to just one LONG or LONG RAW column per table.

 When you insert into a LOB, the actual value of the LOB is stored
in a separate segment (except for in-line LOBs) and only the LOB
locator is stored in the row, thus making it more efficient from a
storage as well as query perspective. With LONG or LONG RAW,
the entire data is stored in-line with the rest of the table row.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Why use LOBs and not LONG or LONG RAW: -

 LOBs allow a random access to its data,


whereas with a LONG you have to go in for a
sequential 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 the
other hand, querying LONG returns the entire
value contained within the LONG column.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
LOB
 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 that


corresponds to the national character set defined for
the database.
 I
 The only external LOB data type in Oracle 8i is called
a BFILE.
 BFILE - Short for Binary File. These hold references to
large binary data stored as physical files in the OS
outside the database.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)

You might also like