You are on page 1of 38

Database Access

1
COMP201, Summer 2007
Database Access : Contents

1. Database Programming using JDBC,

2. Studying Javax.sql.* package,

3. Accessing a Database from a JSP Page,

4. Application – Specific Database Actions,

5. Deploying JAVA Beans in a JSP Page,

2
COMP201, Summer 2007
Database programming using JDBC
A database vendor provides a set of API for accessing the data
managed by the database server.
• Oracle
• Sybase
• Informix etc

Client applications written in native languages such as c/c++


can use these APIs to get direct access to the data.

The JDBC API provides an alternative to using these vendor


specific APIs.

3
COMP201, Summer 2007
This eliminates the need for the java developer to access
vendor-specific APIs.

A JDBC driver is a middleware layer that translates the JDBC


API calls to the vendor specific APIs.

4
COMP201, Summer 2007
Types of JDBC Drivers
Type 1 JDBC Driver:JDBC-ODBC Bridge driver

Type 2 JDBC Driver: Native-API/partly Java driver

Type 3 JDBC Driver: All Java/Net-protocol driver

Type 4 JDBC Driver: Native-protocol/all-Java driver

5
COMP201, Summer 2007
Type 1 JDBC Driver:
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends
them to the ODBC driver.
ODBC is a generic API.
The JDBC-ODBC Bridge driver is recommended only for
experimental use or when no other alternative is available.

6
COMP201, Summer 2007
Type 1: JDBC-ODBC Bridge :Advantages and Disadvantages

Advantages:
1. The JDBC-ODBC Bridge allows access to almost any database, since
the database's ODBC drivers are already available.

Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers
are not portable.

2. A performance issue is seen as a JDBC call goes through the bridge


to the ODBC driver, then to the database, and this applies even in the
reverse process. They are the slowest of all driver types.

3. The client system requires the ODBC Installation to use the driver.

4. Not good for the Web.


7
COMP201, Summer 2007
Type 2 JDBC Driver
Native-API/partly Java driver
Type 2 drivers convert JDBC calls into database-specific calls i.e. this
driver is specific to a particular database.
Some distinctive characteristic of type 2 jdbc drivers are shown
below. Example: Oracle will have oracle native api.

8
COMP201, Summer 2007
Type 2 JDBC Driver: Native-API/partly Java driver
Advantage and Disadvantages
Advantages
1. They typically offer better performance than the JDBC-ODBC Bridge as the
layers of communication (tiers) are less than that of Type 1
2. It uses Native api which is Database specific.

Disadvantages
1. 1. Native API must be installed in the Client System and hence type 2 drivers
cannot be used for the Internet.
2. 2. Like Type 1 drivers, it’s not written in Java Language which forms a
portability issue.
3. 3. If we change the Database we have to change the native api as it is specific
to a database
4. 4. Mostly obsolete now
5. 5. Usually not thread safe.

9
COMP201, Summer 2007
Type 3 JDBC Driver:
All Java/Net-protocol driver
Type 3 database requests are passed through the network to the
middle-tier server.
The middle-tier then translates the request to the database. The middle-
tier server can in turn use Type1, Type 2 or Type 4 drivers.

10
COMP201, Summer 2007
Type 3 JDBC Driver: All Java/Net-protocol driver
Advantages and Disadvantages

Advantages
• 1. This driver is server-based, so there is no need for any vendor database
library to be present on client machines.
2. This driver is fully written in Java and hence Portable and suitable for web.
3. There are many opportunities to optimize portability, performance, and
scalability.
4. The net protocol can be designed to make the client JDBC driver very small
and fast to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one
driver.
7. They are the most efficient amongst all driver types.

11
COMP201, Summer 2007
Type 3 JDBC Driver: All Java/Net-protocol driver
Advantages and Disadvantages (contd.)
• Disadvantages
1. It requires another server application to install and
maintain.
2. Traversing the recordset may take longer, since the data
comes through the backend server.

12
COMP201, Summer 2007
Type 4 JDBC Driver:
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate
directly with the database server.

13
COMP201, Summer 2007
Type 4 JDBC Driver: Native-protocol/all-Java driver
Advantages and Disadvantages
Advantages
• 1. they are completely written in Java to achieve platform
independence and eliminate deployment administration issues. It is
most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers
don't have to translate database requests to ODBC or a native
connectivity interface or to pass the request on to another server,
performance is typically quite good.
3. You don’t need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.

Disadvantage
With type 4 drivers, the user needs a different driver for each database.

14
COMP201, Summer 2007
All types of Drivers

Type IV

Type I

Type II Type III


15
COMP201, Summer 2007
Java application

JDBC API

JDBC Driver manager

JDBC-ODBC Vendor-specific
Bridge JDBC Driver

Vendor-specific
JDBC Driver
Database

Database
16
COMP201, Summer 2007
There are two JDBC driver implementations
• The first approach is a JDBC-ODBC bridge.
• Second approach is a pure java implementation.
A driver that uses the JDBC-ODBC bridge
approach is known as a Type I driver.
• Many databases support Open DataBase
connectivity ( ODBC ) access.
• Jdk includes a JDBC-ODBC bridge to connect
to databases.

17
COMP201, Summer 2007
Pure java drivers are known as Type IV
driver.
The JDBC specification defines two other
driver types , Type II and Type III.

18
COMP201, Summer 2007
The Architecture of JDBC
Java Applications/
Applets

JDBC API

Oracle JDBC JDBC-ODBC


Driver Bridge Driver

Oracle ODBC Microsoft


Driver ODBC Driver

Local or remote Microsoft Access


ORACLE DB Database

19
COMP201, Summer 2007
The JDBC Interfaces

Driver Loading
drivers

Connection Connection Establishing


connections

Creating and
Statement Statement Statement Statement
executing
statements
ResultSet ResultSet ResultSet ResultSet Processing
ResultSet

20
COMP201, Summer 2007
Accessing the database
1. Load the driver :
To load a driver , we will specify the classname of the
database driver in the Class.forName method. By
doing so , it automatically creates a driver instance
and registers with the JDBC driver manager.

Database Driver Class Source


Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK
MySQL com.mysql.jdbc.Driver Website
Oracle oracle.jdbc.driver.OracleDriver Website
Ex: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

21
COMP201, Summer 2007
2. Define the Connection URL
Once we have loaded the driver, we must specify the
location of the database server. URLs referring to
database databases use the jdbc: protocol and embed the
server host, port, and database name ( reference ) with in
the URL.
Examples:
String oracleURL=“jdbc:oracle:thin:@”+host+”:”+port+”:”+dbName;
String sybaseURL=“jdbc:sybase:Tds:@”+host+”:”+port+”:”+dbName;
String msAccessURL=“jdbc:odbc:”+dbName;

Ex: Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger" );
22
COMP201, Summer 2007
3. Establishing the connection
1. To make the actual network connection, pass
the URL, database username and database
password to the getConnection method of the
Driver manager class.

Ex:-
Connection con=
DriverManager.getConnection(oracleURL,
username, password );

23
COMP201, Summer 2007
4. Create a statement object
Statement object is used to send queries to
the database.

Ex:-
Statement stmt=connection.createStatement();

24
COMP201, Summer 2007
5. Execute a query
Once we have a statement object , we can
use it to send SQL queries by using the
execute query method.
Ex:-
String query=“select *from emp”;
ResultSet rs=stmt.executeQuery(query);

25
COMP201, Summer 2007
5. Process the Results
The simplest way to process the results is to use the next
method of ResultSet to move through the table a row at a
time.

ResultSet rs=st.executeQuery("select * from emp");


18. while(rs.next())
19. {
20. pw.println(rs.getString(1)+rs.getString(2)+rs.getString(3));
21. }

26
COMP201, Summer 2007
Developing JDBC Programs
Loading Statement to load a driver:
drivers Class.forName("JDBCDriverClass");
Establishing
A driver is a class. For example:
connections

Creating and Database Driver Class Source


executing Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK
statements MySQL com.mysql.jdbc.Driver Website
Oracle oracle.jdbc.driver.OracleDriver Website
Processing
ResultSet
The JDBC-ODBC driver for Access is bundled in JDK.
MySQL driver class is in mysqljdbc.jar
Oracle driver class is in classes12.jar

To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and
classes12.jar in the classpath using the following DOS command on
Windows:
classpath=%classpath%;c:\book\mysqljdbc.jar;c:\book\classes12.jar
27
COMP201, Summer 2007
Developing JDBC Programs
Loading Connection connection = DriverManager.getConnection(databaseURL);
drivers
Database URL Pattern
Establishing Access jdbc:odbc:dataSource
connections MySQL jdbc:mysql://hostname/dbname
Creating and Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID
executing
statements Examples:
For Access:
Processing Connection connection = DriverManager.getConnection
ResultSet ("jdbc:odbc:ExampleMDBDataSource");

For MySQL:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");

For Oracle:
Connection connection = DriverManager.getConnection
("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger"); 28
COMP201, Summer 2007
Developing JDBC Programs
Loading Creating statement:
drivers Statement statement = connection.createStatement();
Establishing
connections Executing statement (for update, delete, insert):
statement.executeUpdate
Creating and ("create table Temp (col1 char(5), col2 char(5))");
executing
statements Executing statement (for select):
// Select the columns from the Student table
Processing
ResultSet resultSet = statement.executeQuery
ResultSet
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");

29
COMP201, Summer 2007
Developing JDBC Programs
Loading Executing statement (for select):
drivers // Select the columns from the Student table
ResultSet resultSet = stmt.executeQuery
Establishing
("select firstName, mi, lastName from Student where lastName "
connections
+ " = 'Smith'");
Creating and
executing Processing ResultSet (for select):
statements // Iterate through the result and print the student names
while (resultSet.next())
Processing System.out.println(resultSet.getString(1) + " " + resultSet.getString(2)
ResultSet + ". " + resultSet.getString(3));

30
COMP201, Summer 2007
JDBC Class Diagram

31
COMP201, Summer 2007
Accessing a Database from a JSP Page

JSP action elements can be used to access


the database from JSP pages.

32
COMP201, Summer 2007
Employee registration pages

database
COMP201, Summer 2007
33
34
COMP201, Summer 2007
<%@ page language="java" contentType="text/html" %>

<ora:useDataSource id="example"
className="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:dbName" />

<%--
See if the employee is already defined. If not, insert the
info, else update it.
--%>

<ora:sqlQuery id="empDbInfo" dataSource=“dbName">


SELECT * FROM Employee
WHERE <ora:sqlStringValue
param="userNameUserName = ?
" />
</ora:sqlQuery>

35
COMP201, Summer 2007
<% if (empDbInfo.size( ) == 0) { %>

<ora:sqlUpdate dataSource=“dbName">
INSERT INTO Employee
(UserName, Password, FirstName, LastName, Dept,
EmpDate, EmailAddr, ModDate)

VALUES(?, ?, ?, ?, ?, ?, ?, ?)
<ora:sqlStringValue param="userName" />
<ora:sqlStringValue param="password" />
<ora:sqlStringValue param="firstName" />
<ora:sqlStringValue param="lastName" />
<ora:sqlStringValue param="dept" />
<ora:sqlDateValue param="empDate" pattern="yyyy-MM-dd" />
<ora:sqlStringValue param="emailAddr" />
<ora:sqlTimestampValue value="<%= new java.util.Date( ) %>" />

</ora:sqlUpdate>

36
COMP201, Summer 2007
<% } else { %>
<ora:sqlUpdate dataSource=“dbName">
UPDATE Employee
SET Password = ?,
FirstName = ?,
LastName = ?,
Dept = ?,
EmpDate = ?,
EmailAddr = ?,
ModDate = ?
WHERE UserName = ?
<ora:sqlStringValue param="password" />
<ora:sqlStringValue param="firstName" />
<ora:sqlStringValue param="lastName" />
<ora:sqlStringValue param="dept" />
<ora:sqlDateValue param="empDate" pattern="yyyy-MM-dd" />
<ora:sqlStringValue param="emailAddr" />
<ora:sqlTimestampValue value="<%= new java.util.Date( ) %>" />
<ora:sqlStringValue param="userName" />
</ora:sqlUpdate>
<% } %>

37
COMP201, Summer 2007
<%-- Get the new or updated data from the database --%>
<ora:sqlQuery id="newEmpDbInfo" dataSource=“dbName"
scope="session">
SELECT * FROM Employee
WHERE UserName = ?
<ora:sqlStringValue param="userName" />
</ora:sqlQuery>
<%-- Redirect to the confirmation page --%>
<ora:redirect page="confirmation.jsp" />

38
COMP201, Summer 2007

You might also like