You are on page 1of 45

JDBC 3.

Java Database Connectivity

1
Java
Contents

1 JDBC API
2 JDBC Architecture
3 Steps to code
4 Code
5 How to configure the DSN for ODBC Driver for MS-Access
6 Driver Types
7 JDBC-ODBC Bridge
8 Disadvantages
9 Type2- Part Java, Part Native Driver
10 Drivers currently in use

2
Java
Contents

11 Load the driver and get Connection


12 Obtaining Statement
13 Statement
14 Simple ResultSet methods
15 Advanced ResultSet
16 Connection object’s parameterized createStatement() methods
17 Code to work with advanced ResulSet
18 More ResultSet methods
19 PreparedStatement
20 Methods

3
Java
Contents

21 CallableStatement
22 Create the following Stored Procedure in Oracle
23 Java Code to call the stored procedure
24 Transaction support

4
Java
Know
• The JDBC API.
• The different kinds of drivers
• What ResultSet is
• Different types of statements
• Transaction Support

5
Java
Be Able To

• Use JDBC to create data interactive Java


programs
• Implement Transaction Support

6
Java
JDBC API
• JDBC 3.0 part of J2SE 5.0, is an API that
provides a set of generic database access
methods for SQL compliant relational
databases.

Our focus JDBC 3.0

java.sql javax.sql
core extension

7
Java
JDBC Architecture

8
Java
Steps to code
• Load the driver
• Obtain connection
• Create and execute statements
• [Use result sets to navigate the results]
• Close the connection

9
Java
Code
import java.sql.*;
public class ODBCMain{
Connection con;
Data source name (DSN)
public ODBCMain() {
try {
String url = "jdbc:odbc:sample";
Load the JDBC-ODBC bridge dr
Class.forName("sun.jdbc.odbc.JdbcOdbcDr
iver");
con = DriverManager.getConnection(url);

Obtain the
connection to the 10
Folder 1 database Java
Create and execute sql statements

Statement stmt = con.createStatement();


stmt.executeUpdate("INSERT INTO student
VALUES('Shreyas',1234)" );
con.close();
} Close the connection
catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
} }
public static void main(String str[]){
new ODBCMain();
}} 11
Java
How to configure the DSN for ODBC Driver for MS-
Access

• In control panel locate ‘Data


Sources (ODBC)’ icon
• Create the MS-Access table
sample with name(text) and
id(number, primary key).
• Double-click the icon and click
on add button in the ‘User
DSN’ tab.
• Select ‘Microsoft Access Driver’
and click ‘Finish’

click

12
Java
• Enter DSN name as ‘sample’
(same name you have given
in the code) and click
‘Select.’
• Browse through and get the
click
access file and click ok.
• Click ok on next two screens
and come out of the control
panel.

13
Java
Driver Types
• JDBC driver are used to translate JDBC calls
into vendor-specific database calls.
• Types of driver
Type 1- JDBC-ODBC Bridge
Type 2- Part Java, Part Native Driver
Type 3- Intermediate Database Access
Server
Type 4- Pure Java Drivers

14
Java
JDBC-ODBC Bridge

Java
application Database

JDBC JDBC-ODBC ODBC ODBC


API Bridge API Layer

15
Java
Disadvantages
• ODBC uses a C. Calls from Java to native C
code have a number of drawbacks in the
security, robustness, and automatic portability
of applications.
• Multiple layers of indirection leads to
inefficiency.

16
Java
Type2- Part Java, Part Native
Driver

Java
Database
application

Vendor
JDBC JDBC Driver Specific
API API

17
Java
Drivers currently in use

•Type 4 •Type 3
•Two-tier •Three-tier
•Direct to database Pure •JDBC-Net pure Java
Java Driver Driver for Database
middleware

18
Java
Java
application

JDBC Driver Manager or Data Source Object

Pure Java Driver JDBC-Net Pure Java Driver

Database middleware

Database
19
Java
Load the driver and get
Connection
•Register (Load) the driver with the application:
Class.forName("oracle.jdbc.OracleDriver"
);
Or
DriverManager.registerDriver( new
oracle.jdbc.OracleDriver());
•Getting Connection:
DriverManager.getConnection(url);
Or
DriverManager.getConnection(url,username
, password);
20
Java
Obtaining Statement
Connection

createStatement()
Statement

prepareStatement(String s)
PreparedStatement

prepareCall(String sql)
CallableStatement

21
Java
Statement
• public ResultSet executeQuery(String
sql) throws SQLException
SELECT Query
• public int executeUpdate(String sql)
throws SQLException

INSERT, UPDATE, DELETE , CREATE and DROP.

22
Java
Simple ResultSet methods
boolean next() throws SQLException
void close() throws SQLException
XXX getXXX(int columnIndex)
throws SQLException

where XXX is any primitive type,


String, java.sql.Date, Object.

23
Java
import java.sql.*;
public class ODBCMain{
Connection con;
public ODBCMain() {
try {
String url = "jdbc:odbc:sample";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
student");
Folder 2 24
Java
while (rs.next() ) {
String a= rs.getString(1);
int i = rs.getInt(2);
String oneLine = "name " + a + "id= " + i;
System.out.println(oneLine); }
}
catch(Exception e){e.printStackTrace(); }
}
public static void main(String str[]){
new ODBCMain();
}} 25
Java
Advanced ResultSet
• A default ResultSet object is not updatable and
has a cursor that moves forward only.
• In order to have ResultSet which are scrollable
and updatable first we need to use a different
createStatement() method.

26
Java
Connection object’s parameterized
createStatement() methods
• public Statement createStatement(int
resSetType,int resSetConcurrency)
throws
SQLException
• resSetType :
• ResultSet.TYPE_FORWARD_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE_SCROLL_SENSITIVE
• resSetConcurrency :
• ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE
27
Java
Code to work with advanced
ResulSet
import java.sql.*;
public class OracleRS{ URL for oracle database
Connection con; port sid
static final String url
="jdbc:oracle:thin:@sername:1521:sample";
public OracleRS() { Oracle server machine name
try{ password
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection(url,"SYSTEM",
"admin"); User name
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL
_INSENSITIVE, Folder 3 28
ResultSet.CONCUR_UPDATABLE); Java
ResultSet rs = stmt.executeQuery("SELECT
name, id FROM stud");
rs.absolute(2); moves the cursor 2nd row
rs.updateString(1,“BLACK");
rs.updateRow();
updates the row
}
con.close();
catch(Exception e)
{ e.printStackTrace(); }}
public static void main(String str[])
{ new OracleRS();}}
29
Java
More ResultSet methods
boolean absolute(int row)
void afterLast()
void beforeFirst()
void cancelRowUpdates()
void deleteRow()
void insertRow() All throw SQLException
boolean isAfterLast(), boolean isBeforeFirst(),
booleanisFirst(), booleanisLast()
void moveToCurrentRow()
void moveToInsertRow()
void updateRow() 30
Java
31
Java
PreparedStatement
• Subclasses from Statement
• If the same sql statement is executed many
times it is more efficient to use a prepared
statement.
• It enables a SQL statement to contain
parameters like functions. So same statement
can be executed for different set of values.

32
Java
Methods
• public void clearParameters() throws
SQLException
• void setByte(int parameterIndex, byte x)
• void setInt(int parameterIndex, int x)
• void setShort(int parameterIndex, short
x)
• void setLong(int parameterIndex, long x)
• void setDouble(int parameterIndex,
double x)
• void setFloat(int parameterIndex, float
x)
• void setDate void setInt(int
parameterIndex, java.sql.Date d)
• void setString(int parameterIndex, String
33
x) Java
Example
Table name: BookIssue We will use
Column name Type Length PreaparedSta
tement to
----------------------------------------- insert into
BOOKID NUM 10 the this
table. The
REGNO VARCHAR 10 program will
also
demonstrate
ISSUEDATE DATE 4 how to work
with Dates
RETURNDATE DATE 4

34
Java
import java.sql.*;
public class PrepAccess{
Connection con;
public PrepAccess() {
Connection con;
public PrepAccess() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("jdbc:odbc:book");
PreparedStatement stmt =
con.prepareStatement("INSERT INTO BookIssue
VALUES(?,?,?,?)");
stmt.setInt(1,10005);
stmt.setString(2,"To kill a mocking bird");
Folder 4
35
Java
java.util.Calendar
c=java.util.Calendar.getInstance();
c.clear();
c.set(2004,9,25);
stmt.setDate(3,new
java.sql.Date((c.getTime()).getTime()));
c.set(2004,9,27);
stmt.setDate(4,new
java.sql.Date((c.getTime()).getTime()));
stmt.executeUpdate();
stmt.close();} catch(Exception e) {}
public static void main(String str[]){
new PrepAccess(); }}
36
Java
CallableStatement
• Used to execute stored-procedure.
• {call <procedure-name>[<arg1>,<arg2>, ...]}
• IN parameter values are set using the set methods
inherited from PreparedStatement.
• All OUT parameters must be registered before a
stored procedure is executed.
• The example in the next slide demonstrates the use
of Callable statement, input and output parameters.

37
Java
Create the following Stored
Procedure in Oracle
CREATE OR REPLACE PROCEDURE
GETSTUD(id1 IN NUMBER, nm OUT
VARCHAR)
AS
BEGIN
SELECT NAME INTO nm FROM stud
WHERE ID=id1;
END;

38
Java
Java Code to call the stored
procedure
import java.sql.*;
class CallableOracle{
public static void main(String argv[]) {
try {
String url
="jdbc:oracle:thin:@deepa.:1521:sample";
Class.forName("oracle.jdbc.OracleDriver");

Connection con =
DriverManager.getConnection(url,"SYSTEM","
admin");

Folder 5
CallableStatement c=con.prepareCall("{call
39
Java
GETSTUD(?,?)}");
First parameter
String name=null;
c.setInt(1,124);
Value
c.registerOutParameter(
2,java.sql.Types.VARCHAR);
c.executeUpdate();
name=c.getString(2);

System.out.println(" completed successfully


"+ name);

}
catch (Exception e) {
System.out.println(e.toString());
}}
}
40
Java
Transaction support
• Methods in Connection class helps to
demarcate the set of statements into a
transaction.
 public void setAutoCommit(boolean
autoCommit) throws SQLException
 public void rollback() throws
SQLException
 public void commit() throws
SQLException

41
Java
To understand
transactions we
will use two
tables Login ( id,
login, password)
and Student (id,
name). Insertion
of student data
will require us to
insert data either
into both the
tables or in none
of them in case
there is an error. 42
Java
import java.sql.*;
class Trans{
public static void insert(String login,
String pass,int id, String name){
Folder 6
Connection con=null;
try {
String url = "jdbc:odbc:sample";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver
");
con = DriverManager.getConnection(url);
Statement st=con.createStatement(); transaction
con.setAutoCommit(false);
st.executeUpdate("INSERT INTO Login
VALUES("+ id+ ",'"+login+"','"+pass+"')");
st.executeUpdate("INSERT INTO Student
VALUES('"+name+"',"+id+")");
con.commit(); 43
Java
con.close();
} catch(Exception e)
{
try{
System.out.println("Rolling back
Exception :" + e.toString());
con.rollback();
e.printStackTrace();}
catch(Exception e1){}
}
}
public static void main(String[] s){
// insert("emily", "danger", 1,"Emily");
insert("susan", "danger", 1234,"Susan");
}
}
44
Java
Set the id as the
primary key for
the Student and
login as primary
key for table
Login. Test the
application by
giving duplicate
id values
b) without
transaction
statements
c) with transaction
statements 45
Java

You might also like