You are on page 1of 43

JDBC

Java Database Connectivity

Outline of Presentation
Introduction to JDBC
JDBC Driver Types
General Architecture
JDBC Components

Database Programming using JDBC


java.sql.* Package
Accessing Database from a JSP Page
Deploying Java Beans in a JSP Page
Introduction To Struts Framework

Introduction to JDBC
JDBC is a front end tool which is used to connect
front end java application to back end database
JDBC is an alternative to ODBC and ADO that
provides database access to programs written in

Java.
JDBC drivers are available for most DBMS
products

A JDBC Driver
Is an interpreter that translates JDBC method calls to

vendor-specific database commands


Database
commands

JDBC calls
Driver

Database

Implements interfaces in java.sql


Can also provide a vendors extensions to the JDBC

standard

JDBC Driver Types

General Architecture

JDBC Components

Database Programming Using JDBC


STEPS:
1.Load the Driver
2.Establish a connection
3.Create JDBC Statements
4.Execute SQL Statements
5.GET ResultSet
6.Close connections

Using JDBC
1. Load the driver:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//Type1 Driver
2. Establish a connection to the database:
A connection URL string includes the literal jdbc:, followed by the
name of the driver and a URL to the database
String url = "jdbc:odbc:dsn;
Create a Connection object:
Connection con = DriverManager.getConnection(url,
scott,tiger);
3. Create a statement object
Statement stmt = conn.createStatement();
Associate SQL with the statement object
String queryString = select * from emp";

Using JDBC (Continued)


4.Execute the SQL Statements:
Example statements:
ResultSet
rs
=
stmt.executeQuery(querystring);
int
result =
stmt.executeUpdate(updatestring);

Compiled queries can be processed via a PreparedStatement object

Stored procedures can be processed via a CallableStatement object


5. GET Result
while (rs.next()) {
int empno = rs.getInt(1);
String empname = rs.getString(2);
}
6. Close connection
stmt.close();
con.close();

Using a PreparedStatement
// Once you have a connection, you can create a
// "prepared statement" object. A prepared statement is
// precompiled, and can be used repeatedly with new values
// for its parameters.
// Use question marks for parameter place-holders.
PreparedStatement prepStmt = con.prepareStatement(
"INSERT INTO Artist (ArtistID, Name, "
+ "Nationality, BirthDate, DeceasedDate)"
+ "VALUES (ArtistSeq.nextVal, ?, ?, ?, ? )" );
// Now supply values for the parameters
// Parameters are referenced in order starting with 1.
prepStmt.setString( 1, "Galvan" );
prepStmt.setString( 2, "French" );
prepStmt.setInt
( 3, 1910 );
prepStmt.setNull ( 4, Types.INTEGER );
// The PreparedStatement object methods:
// 1) executeUpdate -- statements that modify the database
// 2) executeQuery -- SELECT statements (reads)
prepStmt.executeUpdate();
System.out.println( "Prepared statement executed" );
// Now do it again
prepStmt.setString(
prepStmt.setString(
prepStmt.setInt
(
prepStmt.setInt
(

1,
2,
3,
4,

"Monet" );
"French" );
1840 );
1879 );

prepStmt.executeUpdate();
System.out.println( "Prepared statement executed again" );

Accessing a stored procedure


// Once you have a connection, you can create a
// "callable statement" object to access the stored procedure.
// Inside the curly braces, you call the procedure, and use
// question marks for parameter place-holders.
CallableStatement callStmt = con.prepareCall(
"{call Record_sale( ?, ?, ?, ?, ?, ?)}" );
// Now supply values for the parameters
// Parameters are referenced in order starting with 1.
callStmt.setString( 1, "Barry Goldwater" );
callStmt.setString( 2, "Tobey" );
callStmt.setString( 3, "Mystic Fabric" );
callStmt.setString( 4, "105/135" );
callStmt.setInt
( 5, 24000 );

// And register the OUT variable


// This variable returns information to this program
// from the stored procedure.
callStmt.registerOutParameter( 6, java.sql.Types.VARCHAR );
System.out.println( "Parameters set for CallableStatement" );
// The CallableStatement object has an additional method*
// for use when the stored procedure uses multiple SQL statements.
// 1) executeUpdate -- statements that modify the database
// 2) executeQuery -- SELECT statements (reads)
// *3) execute
-- procedures with multiple SQL statements
callStmt.execute();
System.out.println( "Stored procedure executed" );
// Get the OUT variable contents (parameter 6)
String result = callStmt.getString( 6 );

Java.sql.* package
java.sql.Connection
Statement createStatement (int resultSetType, int resultSetConcurrency)
PreparedStatement prepareStatement (String sql, int resultSetType, int
resultSetConcurrency)
CallableStatement prepareCall (String sql, int resultSetType, int resultSetConcurrency)

resultSetType

resultSetConcurrency

ResultSet.TYPE_FORWARD_ONLY

ResultSet.CONCUR_READ_ONLY

ResultSet.TYPE_SCROLL_INSENSITIVE

ResultSet.CONCUR_UPDATABLE

ResultSet.TYPE_SCROLL_SENSITIVE

Java.sql.* package
java.sql.ResultS
et
void beforeFirst() throws SQLException
void afterLast() throws SQLException
boolean first() throws SQLException

boolean last() throws SQLException


boolean absolute(int row) throws SQLException
boolean relative(int row) throws SQLException

Example : Backward
Statement stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery("SELECT empno, sal FROM emp");


rs.afterLast();
while ( rs.previous() )
{

System.out.println(rs.getString("empno") + " " + rs.getFloat("sal"));


}
...

Accessing the Database using JSP


Consider stocks database
There are three tables. Both customer and stocks have a one-to-many
relationship with portfolios. The database stocks.mdb
was registered with the ODBC driver as CoolStocks

customer stocks portfolio


id
lname
fname

symbol id
company symbol
price
num_shares

Register w/ODBC
Create an ODBC data source.
Click on the Start button.
Choose Settings, Control Panel
Double-click on ODBC Data Sources
Choose the System DSN tab
Click Add
Click on the desired driver (Microsoft ODBC for oracle)
Click on the Finish button
Enter a Data Source Name (I called my database CoolStocks
and that name appears in the java code below)

A Simple JSP/JDBC Example


<TITLE>JSP JDBC Example 1</TITLE>
</HEAD>
<BODY>
<! Adapted from James Goodwills Pure JSP
<!-- Set the scripting language to java and -->
<!-- import the java.sql package -->
<%@ page language="java" import="java.sql.*" %>
<%@ page import= "java.io.*" %>

<%
Connection con = null;
try {
// Load the Driver class file
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Make a connection to the ODBC datasource Movie Catalog
con = DriverManager.getConnection("jdbc:odbc:CoolStocks,scott,tiger);
// Create the statement
Statement statement = con.createStatement();
// Use the created statement to SELECT the DATA
// FROM the customer Table.
ResultSet rs = statement.executeQuery("SELECT * " +
"FROM customer");
// Iterate over the ResultSet
%>

<!-- Add an HTML table to format the results -->


<TABLE BORDER="1">
<TR>
<TH> Customer - ID</TH><TH>Last Name</TH>
<TH>First Name</TH>
<%
while ( rs.next() ) {
// get the id, convert to String
out.println("<TR>\n<TD>" + rs.getString("id") + "</TD>");
// get the last name
out.println("<TD>" + rs.getString("lname") + "</TD>");
// get the first name
out.println("<TD>" + rs.getString("fname") + "</TD>\n</TR");
}

// Close the ResultSet


rs.close();
}
catch (IOException ioe) {
out.println(ioe.getMessage());
}
catch (SQLException sqle) {
out.println(sqle.getMessage());
}
catch (ClassNotFoundException cnfe) {
out.println(cnfe.getMessage());
}
catch (Exception e) {
out.println(e.getMessage());
}

finally {
try {
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
out.println(sqle.getMessage());
}
}
%>
</BODY>
</HTML>

It Works!(output)

Using JavaBeans in JSP

To use a JavaBean in your JSP page, you need


to:

Include the JavaBean reference in the JSP


page
Set the JavaBean property
Get the JavaBean property

Using JavaBeans in JSP (Contd.)

Including Bean Reference

You can use the JSP action tag, <jsp:useBean> to include a bean
reference in your JSP page.
The <jsp:useBean> action tag creates an instance of the JavaBean and
stores the bean reference in a variable.
The variable can then be used to access the JavaBean throughout the JSP
page.
The following code snippet shows the syntax of the <jsp:useBean> action
tag:
<jsp:useBean
id=Bean Name
scope=ScopeName
class=class name />

Using JavaBeans in JSP (Contd.)

Scope of JavaBean in a JSP page

page: Specifies that the JavaBean object is available only

for the current page. The following code snippet shows


the <jsp:useBean> action tag that includes a bean with a
page scope:
<jsp:useBean id="option_bean" scope =page
class="test.OptionBean"/>

request: Specifies that the JavaBean object is available

for the current request. The following code snippet shows


the <jsp:useBean> action tag that includes a bean with a
request scope:
<jsp:useBean id="option_bean" scope =request
class="test.OptionBean"/>

Using JavaBeans in JSP (Contd.)


session: Specifies that the JavaBean object is available only for
the current session. The following code snippet shows the
<jsp:useBean> action tag that includes a bean with a session
scope:
<jsp:useBean id="option_bean" scope =session
class="test.OptionBean"/>

application: Specifies that the JavaBean object is available for the


entire Web application. The following code snippet shows the
<jsp:useBean> action tag that includes a bean with an
application scope:
<jsp:useBean id="option_bean" scope =application
class="test.OptionBean" />

Using JavaBeans in JSP (Contd.)

Setting Beans Properties

The <jsp:setProperty> tag enables you to set properties for


a JavaBean to specific values.
The <jsp:setProperty> tag can be defined inside
<jsp:useBean> tag or anywhere in the JSP file after the
declaration of <jsp:useBean> tag.
The following syntax shows how to set a property of a
JavaBean using <jsp:setProperty> tag:
<jsp:setProperty name=beanName property=
propertyName>

Using JavaBeans in JSP (Contd.)

The following table describes various attributes of the <jsp:setProperty>


tag:

Attribute

Description

name

Specifies the name of the bean object. The value of this


attribute should be the same as the value of the id attribute
of the <jsp:useBean> tag.

property

Represents the name of JavaBean property to be set.

Using JavaBeans in JSP (Contd.)

Reading Bean Properties

The <jsp:getProperty> action tag is used to read the value of a


JavaBean property in your JSP page.
The value returned by the tag, <jsp:getProperty> is converted into
java.lang.String and is placed into an implicit object, out.
The following syntax shows how to get the JavaBean property using
the <jsp:getProperty> tag:
<jsp:getProperty name=beanName property=propertyName />

Using JavaBeans in JSP (Contd.)

The following table describes various attributes of the <jsp:getProperty>


tag:

Attribute

Description

name

Represents the name of the JavaBean object.

property

Represents the bean property for which you want to retrieve the
value.

Demonstration-Implementing
JavaBeans in JSP

Problem Statement

Create a JSP application that connects to a database and retrieve


the details, such as author id, address, city, state, and zip code
related to authors. The JavaBean component should accept the
author id, driver name, and URL as a parameter. The information is
to be retrieved from authors table.

Demonstration-Implementing
JavaBeans in JSP (Contd.)

Solution

To solve the given problem, perform the following task:


1.
2.
3.
4.

Create a JavaBean that implements the business logic.


Create a JSP page that instantiates a JavaBean.
Create the user interface using HTML.
Access the JSP application.

Struts Frame work


Struts is an open-source framework for building more flexible,

maintainable

and structured front-ends in Java web applications

There are two key components in a web application:


the data and business logic performed on this data
the presentation of data

Struts
helps structuring these components in a Java web app.

controls the flow of the web application, strictly separating

these components
unifies the interaction between them
This separation between presentation, business logic and control is

achieved
by implementing the Model-View-Controller (MVC)
Design Pattern

The Model-View-Controller Pattern - Overview


Splits up responsibilities for handling user interactions in an application into
three layers:
Model, View, Controller

Model
holds application data and business logic

is absolutely independent from the UIs

The Model-View-Controller Pattern - Details


View
presentation of parts of the Model to the user
independent from the internal implementation of the Model
there can be different Views presenting the same Model data

Controller
bridge between Model and View
controls the flow of the application

receives/interprets user input


performs operations on the Model
triggers View update

Benefits:
better maintainability and testability of applications
ability to easily develop different kinds of UIs (e.g. console, GUI, )
separation of different tasks in development
code reusability

Controller ActionServlet
The central component in a Struts application
manages the flow of the application
receives user requests and delegates

them

to the corresponding Action classes


selects the appropriate View to be displayed next
(according to ActionForward returned by an Action class)
represents a Single Point of Entry of the web application

(Front Controller Pattern)


implemented as a simple Java Servlet
listed in the deployment descriptor of the surrounding Web

Container (usually web.xml) for handling *.do requests


can be extended, but in most cases this is not necessary

Controller Actions
perform logic depending on a users request
Actions
are Java classes that extend Struts Action

class org.apache.struts.action.Action
The Action's execute() method is called by
the ActionServlet
Tasks are usually performed by Actions:
depending on the type of action:

perform the action directly (non-complex actions)


call one or more business logic methods in the Model
return an appropriate ActionForward object that tells the
ActionServlet which View component it should forward to
Ex.: failure or success in login application

Controller ActionForms
represent the data stored in HTML forms
hold the state of a form in their properties
provide getter/setter methods to access them
may provide a method to validate form data

ActionForms
are Java classes that extend Struts ActionForm

class org.apache.struts.action.ActionForm
are filled with the form data by the ActionServlet
one ActionForm can be used for more than one HTML form
very useful when building wizards or similar types of forms

Controller ActionForms Validating user input


Validation is done
right in the beginning before the data is used by any business

methods (at this point, validation is limited to the data structure!)


Struts offers two options for server-side validation of user input:
the validate() method in ActionForms
can

be implemented by the ActionForm developer


returns either null (no errors) or an ActionErrors object
a plug-in to use the Jakarta Commons Validator within Struts
based on rules defined in an XML file
there can be one or more rules associated with each property in
a form
rules can define required fields, min./max. length, range, type
error messages and rules can be localized using resource
bundles

View JSPs with Struts tag libraries


The presentation layer in a Struts

application is created using standard JSPs


together with some Struts Tag Libraries
Struts tag libraries
provide access to Model data
enable interaction with ActionForms
provide simple structural logic (such as iteration)
Example:

...

<%@ prefix="html" uri="/WEB-INF/struts-html.tld" %>


<body>
<html:errors/>
<html:form action="login.do">
Username: <html:text property="username"/><br/>
Password: <html:password property="passwd"
redisplay="false"/><br/>
<html:submit>Login</html:submit>
</html:form>
</body>

The Model
Holds the data of an application and provides
business logic methods
Not directly part of the Struts framework!
The Model is usually built of different kinds
of Business Objects:
JavaBeans
simple

Java classes, that follow certain naming conventions


contain attributes and corresponding getters/setters
reside in the Web Container
Enterprise JavaBeans (EJBs)
components containing business logic in a J2EE architecture
reside in an EJB Container
kinds of EJBs: Session Beans, Entity Beans, Message Driven
Beans

Important Questions
1. Explain Different Types of JDBC Drivers
2. Explain the process of Accessing Database from a
JSP Page
3. Explain Struts Framework
4. Explain Deploying of Java Beans in a JSP Page
5. Explain Java.sql.* package
6. Explain Various types of ResultSets with example

You might also like