Professional Documents
Culture Documents
Database Programming
with Java
04e-BM/NS/HDCV/FSOFT v2/3
Course Objective
JDBC Basics
Basic steps in using JDBC
Statement
ResultSet
PreparedStatement
JDBC Advanced
Handling SQLExceptions
Batch update
Transaction
RowSet
Stored Procedures
Connection pool
Guide
04e-BM/NS/HDCV/FSOFT v2/3
Learning Approach
04e-BM/NS/HDCV/FSOFT v2/3
Session 1
JDBC BASICS
04e-BM/NS/HDCV/FSOFT v2/3
JDBC
JDBC (Java DataBase
Connectivity) provides a
standard library for
accessing relational
databases
JDBC consists of two parts:
04e-BM/NS/HDCV/FSOFT v2/3
Advantages of JDBC
Continued usage of existing data
Vendor independent
Platform independent
Ease of use
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
DriverXYZ());
o
o
Class.forName("DriverXYZ");
o
o
Some examples.
Class.forName("oracle.jdbc.driver.OracleDriv
er");
o Class.forName("org.gjt.mm.mysql.Driver");
o Class.forName(com.mysql.jdbc.Driver");
o Class.forName(com.ibm.db2j.jdbc.DB2jDriv
o
04e-BM/NS/HDCV/FSOFT v2/3
Examples:
o
o
jdbc:oracle:thin:@localhost:1521:orcl
jdbc:mysql://127.0.0.1:3306/books
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
ResultSet object
A ResultSet object is a table of data
representing a database result set,
which is usually generated by
executing a statement that queries the
database.
You access the data in a ResultSet
object through a cursor. This cursor is a
pointer that points to one row of data
in the ResultSet. Initially, the cursor is
positioned before the first row.
04e-BM/NS/HDCV/FSOFT v2/3
ResultSet type
04e-BM/NS/HDCV/FSOFT v2/3
ResultSet Concurrency
The concurrency of a ResultSet object
determines what level of update
functionality is supported.
There are two concurrency levels:
04e-BM/NS/HDCV/FSOFT v2/3
Cursor Holdability
04e-BM/NS/HDCV/FSOFT v2/3
ResultSet navigation
Method
Description
next()
previous()
first()
last()
beforeFirst()
afterLast()
getRow()
04e-BM/NS/HDCV/FSOFT v2/3
Description
absolute(int
row)
relative(int
rows)
public Statement
createStatement(intresultSetType,
intresultSetConcurrency) throws SQLException
public PreparedStatement
prepareStatement(Stringsql,
intresultSetType, intresultSetConcurrency)
throws SQLException
public CallableStatement
prepareCall(Stringsql, intresultSetType,
intresultSetConcurrency) throws SQLException
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
Updating a row
Statement st =
cn.createStatement(ResultSet.TYPE_SCROLL_SENS
ITIVE, ResultSet.CONCUR_UPDATABLE)
ResultSet rs = st.executeQuery(SELECT NAME,
EMPLOEE_ID FROM EMPLOYEES);
rs.first();
rs.updateInt(2,2345); //rs.update<Type>
rs.updateRow();
04e-BM/NS/HDCV/FSOFT v2/3
Inserting a row
Statement st =
cn.createStatement(ResultSet.TYPE_SCROLL_SEN
SITIVE, ResultSet.CONCUR_UPDATABLE)
ResultSet rs = st.executeQuery(SELECT NAME,
EMPLOEE_ID FROM EMPLOYEES);
rs.first();
rs.update<Type>
rs.insertRow();
04e-BM/NS/HDCV/FSOFT v2/3
Deleting a row
Step 1: Positioning the cursor
// Move the cursor to the last row of the
result set
rs.last();
rs.deleteRow();
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
DisplayAuthors
o
o
04e-BM/NS/HDCV/FSOFT v2/3
DisplayAuthors.java
1 // DisplayAuthors.java
2 // Displaying the contents of the authors table.
3
4 import java.awt.*;
5 import java.sql.*;
6 import java.util.*;
7 import javax.swing.*;
8
9 public class DisplayAuthors extends JFrame {
10
11 // JDBC driver name and database URL
12 static String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
13 String DATABASE_URL = "jdbc:oracle:thin:@localhost:1521:orcl";
14
15 // declare Connection and Statement for accessing
16 // and querying database
17 private Connection connection;
18 private Statement statement;
19
20 // constructor connects to database, queries database, processes
21 // results and displays results in window
22 public DisplayAuthors()
23 {
24 super( "Authors Table of Books Database" );
25
04e-BM/NS/HDCV/FSOFT v2/3
DisplayAuthors.java
26
27
28
29
30
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
04e-BM/NS/HDCV/FSOFT v2/3
DisplayAuthors.java
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
04e-BM/NS/HDCV/FSOFT v2/3
DisplayAuthors.java
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
04e-BM/NS/HDCV/FSOFT v2/3
DisplayAuthors.java
98 // handle exceptions closing statement and connection
99 catch ( SQLException sqlException ) {
100 JOptionPane.showMessageDialog( null,
101 sqlException.getMessage(), "Database Error",
102 JOptionPane.ERROR_MESSAGE );
103
104 System.exit( 1 );
105 }
106 }
107
108 } // end DisplayAuthors constructor
109
110 // launch the application
111 public static void main( String args[] )
112 {
113 DisplayAuthors window = new DisplayAuthors();
114 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
115 }
116
117 } // end class DisplayAuthors
04e-BM/NS/HDCV/FSOFT v2/3
PreparedStatement Object
An object that represents a precompiled
SQL statement.
PreparedStatement object is given an SQL
statement when it is created. This SQL
statement is sent to the DBMS right away,
where it will be compiled.
When the PreparedStatement is executed,
the DBMS can just run the
PreparedStatement 's SQL statement
without having to compile it first.
PreparedStatement objects are used more
for SQL statements that take parameters.
The advantage of using SQL statements that
take parameters is that you can use the
same statement and supply it with different
04e-BM/NS/HDCV/FSOFT v2/3
PreparedStatement Example
PreparedStatement pstmt = con.prepareStatement(
"UPDATE authors
SET lastName = ?
WHERE authorID = ?");
pstmt.setString(1, John);
pstmt.setInt(2, 3);
pstmt.executeUpdate();
04e-BM/NS/HDCV/FSOFT v2/3
Session 2
JDBC ADVANCED
04e-BM/NS/HDCV/FSOFT v2/3
Handling SQLExceptions
A SQLState code.
These codes and their respective meanings have been standardized by ISO/ANSI
and Open Group (X/Open), although some codes have been reserved for database
vendors to define for themselves. This String object consists of five alphanumeric
characters. Retrieve this code by calling the method SQLException.getSQLState.
An error code.
This is an integer value identifying the error that caused the SQLException
instance to be thrown. Its value and meaning are implementation-specific and
might be the actual error code returned by the underlying data source. Retrieve
the error by calling the method SQLException.getErrorCode.
A cause.
A SQLException instance might have a causal relationship, which consists of one
or more Throwable objects that caused the SQLException instance to be thrown.
To navigate this chain of causes, recursively call the method
SQLException.getCause until a null value is returned.
04e-BM/NS/HDCV/FSOFT v2/3
Retrieving Exceptions
04e-BM/NS/HDCV/FSOFT v2/3
Retrieving Exceptions
SQLState: 42Y55
Error Code: 30000
Message: 'DROP TABLE' cannot be performed on
BOOKS.SAMPLEAUTHORS' because it does not exist.
04e-BM/NS/HDCV/FSOFT v2/3
Batch updates
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
Introduction to Transactions
Concept of Transaction:
One or more statement executed
together
Indivisible unit of work
Properties of Transaction
Atomicity
Consistency
Isolation
Durability
04e-BM/NS/HDCV/FSOFT v2/3
Transaction
04e-BM/NS/HDCV/FSOFT v2/3
Transaction Processing
Start transaction
Disable auto-commit mode
The way to allow two or more statements to be grouped into a
transaction is to disable the auto-commit mode.
con.setAutoCommit(false);
Perform transaction
Execute queries
Committing transaction
Commit
After the auto-commit mode is disabled, no SQL statements are
committed until you call the method commit() explicitly. All statements
executed after the previous call to the method commit() are included in
the current transaction and committed together as a unit.
Rollback transaction
If any error of abnormal case happened, you may want to aborts this
transaction and restores values to what they were before the
attempted update:
con.rollback()
04e-BM/NS/HDCV/FSOFT v2/3
To remove a savepoint:
con.releaseSavepoint(Savepoint savepoint)
To rollback to a savepoint:
rollback(Savepoint savepoint)
04e-BM/NS/HDCV/FSOFT v2/3
RowSet
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
Setting Up Listeners
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
04e-BM/NS/HDCV/FSOFT v2/3
Stored Procedures
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
Connection pool
A connection pool is a cache of
database connections maintained so
that the connections can be reused
when future requests to the
database are required.
Connection pools are used to
enhance the performance of
executing commands on a database.
54
04e-BM/NS/HDCV/FSOFT v2/3
Connection pool
55
04e-BM/NS/HDCV/FSOFT v2/3
Connection pool
Client 1
Connection
pool
Databas
e
56
04e-BM/NS/HDCV/FSOFT v2/3
Connection pool
Client 1
Client 2
Connection
pool
Databas
e
57
04e-BM/NS/HDCV/FSOFT v2/3
Connection pool
Client 2
Connection
pool
Databas
e
58
04e-BM/NS/HDCV/FSOFT v2/3
Connection pool
Client 3
Client 2
Connection
pool
Databas
e
59
04e-BM/NS/HDCV/FSOFT v2/3
How to implement?
You may write your own code
You may using Application server
which supported connection pool (for
ex: Tomcat, Jboss, Jetty, )
You may using other libraries
60
04e-BM/NS/HDCV/FSOFT v2/3
Application server
61
04e-BM/NS/HDCV/FSOFT v2/3
In the web.xml:
<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances
</description>
<res-ref-name>
jdbc/EmployeeDB
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
62
04e-BM/NS/HDCV/FSOFT v2/3
Tomcat configuration
63
04e-BM/NS/HDCV/FSOFT v2/3
64
04e-BM/NS/HDCV/FSOFT v2/3
65
04e-BM/NS/HDCV/FSOFT v2/3
HSQL in-memory
Guide to use HSQL in-memory.doc
SampleHSQL.jar
SampleHSQL.zip
MySQL
Guide to use MySQL.doc
MysqlConnect.java
04e-BM/NS/HDCV/FSOFT v2/3
Summary
04e-BM/NS/HDCV/FSOFT v2/3
Summary(cont)
04e-BM/NS/HDCV/FSOFT v2/3
Q&A
69
04e-BM/NS/HDCV/FSOFT v2/3