Java Chapter 7 and 8 JDBC and Servelets
Java Chapter 7 and 8 JDBC and Servelets
JDBC
Java Database Connectivity (JDBC) is an Application
Programming Interface (API) used to connect Java application
with Database.
It is used to interact with the various type of Database such as
Oracle, MS Access, My SQL and SQL Server and it can be stated
as the platform-independent interface between a relational
database and Java programming.
1
JDBC…
JDBC is the Java API for accessing relational database.
The JDBC API can also be used to interact with multiple data sources
The JDBC API is a set of Java interfaces and classes used to write Java
2
programs for accessing and manipulating relational databases.
General Structure of JDBC
3
JDBC
Since a JDBC driver serves as the interface to facilitate
communications between JDBC and a proprietary database, JDBC
drivers are database specific and are normally provided by the
database vendors.
You need MySQL JDBC drivers to access the MySQL database, and
Oracle JDBC drivers to access the Oracle database.
For the access database, use the JDBC-ODBC bridge driver
included in the JDK.
ODBC is a technology developed by Microsoft for accessing
databases on the Windows platform. An ODBC driver is
preinstalled on Windows.
The JDBC-ODBC bridge driver allows a Java program to access any
ODBC data source.
The relationships between Java programs, JDBC API, JDBC drivers,
4
and relational databases are shown in Figure below.
JDBC
Why Java for Database Programming?
First, Java is platform independent. You can develop platform-
independent database applications using SQL and Java for any
relational database systems.
Second, the support for accessing database systems from Java is built
into Java API, so you can create database applications using all Java
code with a common interface.
The Architecture of JDBC
6
JDBC Architecture
Two-tier model Three-tier model
• The Java applet or application • Provides a middle tier.
talks directly to the database. • The middle tier can help
• This is a client/server model businesses maintain control of
where the application is the the database accesses.
client, and the database is the
server.
7
Developing Database Applications Using JDBC
The JDBC API is a Java application program interface to generic SQL databases that
interface.
The JDBC API consists of classes and interfaces for establishing connections with
databases, sending SQL statements to databases, processing the results of SQL statements,
Four key interfaces are needed to develop any database application using Java: Driver,
The JDBC API defines these interfaces, and the JDBC driver vendors provide the
8
implementation for the interfaces.
Developing Database Applications Using JDBC
A JDBC application:
10
Developing JDBC Programs
Loading Statement to load a driver:
drivers Class.forName("JDBCDriverClass");
To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and
classes12.jar in the class path.
11
Developing JDBC Programs
Loading Connection connection = DriverManager.getConnection(databaseURL);
drivers
Database: URL Pattern
Establishing Access : jdbc:odbc:dataSource
connections MySQL: jdbc:mysql://hostname:port# /dbname, username, password
Oracle: jdbc:oracle:thin:@hostname:port#:oracleDBSID, username, pwd
Creating and
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");
12
Developing JDBC Programs
Loading Creating statement:
drivers Statement statement = connection.createStatement();
Establishing
connections
Executing statement (for update, delete, insert):
statement.executeUpdate ("create table Temp (col1 char(5), col2
Creating and 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'");
13
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));
14
Processing SQL Statements with
JDBC
• In general, to process any SQL statement with
JDBC, you follow these steps:
1)Establish a connection.
2)Create a statement.
3)Execute the query.
4)Process the ResultSet object.
5)Close the connection.
15
Establishing a connection
• First, establish a connection with the data source you
want to use.
• A data source can be a DBMS, a legacy file system, or
some other source of data with a corresponding JDBC
driver.
• This connection is represented by a Connection object.
• java.sql.Connection interface corresponds to a session
(a connection with a specific database).
• DriverManager will create a Connection object.
Connection con = DriverManager.getConnection
"jdbc:myDriver:myDatabase",username,password);
16
Creating a statement
• A Statement is an interface that represents a SQL
statement.
• You execute Statement objects, and they generate
ResultSet objects, which is a table of data representing
a database result set.
• You need a Connection object to create a Statement
object.
17
Executing Queries
• You can call the following three methods on a
Statement object to execute SQL queries/statements:
• execute - returns true if the first object that the query
returns is a ResultSet.
• This method can return multiple ResultSet objects, which can
be retrieved by repeatedly calling getResultSet on it.
• executeQuery - returns one ResultSet object.
• Used for the SELECT SQL statement.
• executeUpdate - returns an integer representing the
number of rows effected by the SQL statement.
• Used for the UPDATE, INSERT and DELETE SQL
statements.
18
Processing ResultSet Objects
• A ResultSet is returned when you execute an SQL
statement:
ResultSet rs = stmt.executeQuery("SELECT *
FROM
Employees");
19
Closing Connections
• When you are finished using a Statement, call the
method Statement.close to immediately release the
resources it is using.
• When you call this method, its ResultSet objects
are closed.
• A typical statement for closing a connection:
if (stmt != null) {
stmt.close();
}
20
Example
public void connectToAndQueryDatabase(
String username, String password) {
Connect to the
Connection con = DriverManager.getConnection database
("jdbc:myDriver:myDatabase", username, password);
Create a Statement object
Statement stmt = con.createStatement(); which will execute a query
on the database
ResultSet rs = stmt.executeQuery(
Get the results of
"SELECT * FROM Employees");
while (rs.next()) { executing that statement
as a ResultSet object
int id = rs.getInt("ID_Number");
String fName = rs.getString("First_Name"); Iterate through the
String lName = rs.getString("Last_Name"); rows in the ResultSet
}
21
Developing JDBC Programs
• The getString(1) , getString(2) , and getString(3)
methods retrieve the column values for firstName, mi ,
and lastName, respectively.
25
The execute(), executeQuery(), and executeUpdate() Methods
• The Statement interface is used to execute static SQL statements that don’t
contain any parameters.
representing values for firstName, mi , and lastName in a record of the Student table.
• It also provides the methods for setting parameters in the object of PreparedStatement.
• These methods are used to set the values for the parameters before executing statements or
procedures. In general, the set methods have the following name and signature:
• where X is the type of the parameter, and parameterIndex is the index of the parameter in the
• For example, the method setString(int parameterIndex, String value) sets a String value to the
specified parameter. 29
PreparedStatement
• The following statements pass the parameters "Jack", "A", and "Ryan” to the placeholders
preparedStatement.setString(1, "Jack");
preparedStatement.setString(2, "A");
preparedStatement.setString(3, "Ryan");
• After setting the parameters, you can execute the prepared statement by invoking
executeQuery() for a SELECT statement and executeUpdate() for a DDL or update statement.
• The executeQuery() and executeUpdate() methods are similar to the ones defined in the
Statement interface except that they don’t have any parameters, because the SQL statements
PreparedStatement is created. 30
Example: PreparedStatement to Execute Dynamic SQL Statements
import javax.swing.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class FindGradeUsingPreparedStatement extends JApplet {
private JTextField jtfSSN = new JTextField(9);
private JTextField jtfCourseId = new JTextField(5);
private JButton jbtShowGrade = new JButton("Show Grade");
System.out.println("Database connected");
32
Example: PreparedStatement to Execute Dynamic SQL Statements
catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbtShowGrade_actionPerformed(ActionEvent e) {
String ssn = jtfSSN.getText();
String courseId = jtfCourseId.getText();
try {
preparedStatement.setString(1, ssn);
preparedStatement.setString(2, courseId);
ResultSet rset = preparedStatement.executeQuery();
if (rset.next()) {
String lastName = rset.getString(1);
String mi = rset.getString(2);
String firstName = rset.getString(3);
String title = rset.getString(4);
String grade = rset.getString(5);
// Connect to a database
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");
System.out.println("Database connected");
38
Example: Obtaining Database Tables
import java.sql.*;
public class FindUserTables {
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
// Connect to a database
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");
System.out.println("Database connected");
• You can use the getColumnCount() method to find the number of columns
in the result and the getColumnName(int) method to get the column
names.
• The following program displays all the column names and contents
resulting from the SQL SELECT statement select * from Enrollment.
40
Example: Result Set Metadata
import java.sql.*;
public class TestResultSetMetaData {
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
// Connect to a database
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook", "scott", "tiger");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select * from Enrollment");
ResultSetMetaData rsMetaData = resultSet.getMetaData();
for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
System.out.printf("%-12s\t", rsMetaData.getColumnName(i));
System.out.println();
// Iterate through the result and print the students' names
while (resultSet.next()) {
for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
System.out.printf("%-12s\t", resultSet.getObject(i));
System.out.println();
}
// Close the connection
connection.close();
}
41
}
DatabaseMetadata, cont.
42
General Information
43
DatabaseMetaData dbMetaData = connection.getMetaData();
System.out.println("database URL: " + dbMetaData.getURL());
System.out.println("database username: " +
dbMetaData.getUserName());
System.out.println("database product name: " +
dbMetaData.getDatabaseProductName()); Examples
System.out.println("database product version: " +
dbMetaData.getDatabaseProductVersion());
System.out.println("JDBC driver name: " +
dbMetaData.getDriverName());
System.out.println("JDBC driver version: " +
dbMetaData.getDriverVersion());
System.out.println("JDBC driver major version: " +
new Integer(dbMetaData.getDriverMajorVersion()));
System.out.println("JDBC driver minor version: " +
new Integer(dbMetaData.getDriverMinorVersion()));
System.out.println("Max number of connections: " +
new Integer(dbMetaData.getMaxConnections()));
System.out.println("MaxTableNameLentgh: " +
new Integer(dbMetaData.getMaxTableNameLength()));
System.out.println("MaxColumnsInTable: " +
new Integer(dbMetaData.getMaxColumnsInTable()));
connection.close();
44
Chapter 8 : Servlets
• There are different types of Web Technologies in Java, of
which the following are the most well-known
technologies.
1. Servlet
2. Java Server Page (JSP)
3. Java Server Face(JSF)
45
Objectives
• To understand the concept of servlets.
• To run servlets with Tomcat.
• To know the servlets API.
• To create simple servlets.
• To create and process HTML forms.
• To develop servlets to access databases.
• To use hidden fields, cookies, and HttpSession to
track sessions.
• To send images from servlets.
46
Introduction
• What is a web application?
• A web application is an application accessible from the web.
• A web application is composed of web components like Servlet, JSP, JSF, etc.
and other elements such as HTML, CSS, and JavaScript.
• The web components typically execute in Web Server and respond to the HTTP
request.
• Website
• Website is a collection of related web pages that may contain text, images, audio
and video.
• The first page of a website is called home page.
• Each website has specific internet address (URL) that you need to enter in your
browser to access a website.
• Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network.
• A website is managed by its owner that can be an individual, company or an
organization.
• A website can be of two types:
• Static Website /Web Content
47
• Dynamic Website /Web Content
Static website/Web Content
48
Dynamic website/Web Content
• Dynamic website is a collection of dynamic web pages whose content changes dynamically.
• It accesses content from a database or Content Management System (CMS).
• Therefore, when you alter or update the content of the database, the content of the website is also altered or updated.
• Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content.
• Client side scripting generates content at the client computer on the basis of user input.
• The web browser downloads the web page from the server and processes the code within the page to render
information to the user.
• In server side scripting, the software runs on the server and processing is completed in the server then plain pages are
sent to the user. Dynamic Web pages are generated by Web servers.
• Example:
• Stock quotes are updated whenever a trade takes place.
• Election vote counts are updated constantly on Election Day.
• Weather reports are frequently updated.
• The balance in a customer’s bank account is updated whenever a transaction takes place.
49
Static vs Dynamic website
50
HTTP (Hyper Text Transfer Protocol)
51
The Basic Architecture of HTTP
• HTTP is request/response protocol which is based on client/server based architecture.
• In this protocol, web browser, search engines, etc. behave as HTTP clients and the Web
server like Servlet behaves as a server
• The below diagram represents the basic architecture of web application and depicts where
HTTP stands:
52
Servlet
• Servlet technology is used to create a web application
(resides at server side and generates a dynamic web page).
• Servlet technology is robust and scalable because of java
language.
• Servlets are Java programs that run on a Web server.
• Servlets can be used to process client requests or produce
dynamic Web pages.
• JSP, JSF, and Java Web services are based on servlets.
• Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side
programming language.
53
CGI (Common Gateway Interface)
• CGI technology enables the web server to call an external program and pass HTTP
request information to the external program (CGI Program) to process the request.
• For each request, it starts a new process.
• CGI was proposed to generate dynamic Web content.
• The CGI program processes the request and generates a response at runtime.
• Disadvantages of CGI
• There are many problems in CGI technology:
• If the number of clients increases, it takes more time for sending the response.
• For each request, it starts a process, and the web server is limited to start processes.
• It uses platform dependent language e.g. C, C++, perl.
54
Advantages of Servlet
55
CGI vs. Servlets
59
GET and POST
• The GET and POST methods both send requests to the Web
server.
• The POST method always triggers the execution of the
corresponding the servlet program.
• The GET method may not cause the servlet program to be
executed, if the previous same request is cached in the Web
browser.
• Web browsers often cache Web pages so that the same request
can be quickly responded to without contacting the Web server.
• To ensure that a new Web page is always displayed, use the
POST method.
• For example, use a POST method if the request will actually
update the database.
• If your request is not time sensitive use the GET method to
speed up performance. 60
GET vs POST
GET POST
1) In case of Get request, only limited In case of Post request, large amount of
amount of data can be sent because data data can be sent because data is sent in
is sent in header. body.
2) Get request is not secured because Post request is secured because data is
data is exposed in URL bar. not exposed in URL bar.
5) Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.
61
The Servlet API
63
The Servlet Interface
• The javax.servlet.Servlet interface defines the methods that all servlets must
implement. The methods are listed below:
1. The init method is called when the servlet is first created and
is not called again as long as the servlet is not destroyed.
2. The service method is invoked each time the server receives a
request for the servlet. The server spawns/produces/generates
a new thread and invokes service.
65
Servlet Life Cycle
The JVM uses the init, service, and destroy methods to control the
servlet.
66
The GenericServlet Class
71
The ServletRequest Interface
72
The HttpServletResponse Interface
73
The HttpServletResponse Interface
74
Creating Servlets
75
Creating Servlets
76
Creating Servlets
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CurrentTime extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<p>The current time is " + new
java.util.Date());
// Close stream
out.close();
}
}
79
HTML Forms
80
HTML tags to construct HTML forms
1. <form>
• <form> ... </form> defines a form body.
• The attributes for the <form> tag are action and method.
• The action attribute specifies the server program to be executed
on the Web server when the form is submitted.
• The method attribute is either get or post.
2. <label>
• <label> ... </label> simply defines a label.
81
HTML tags to construct HTML forms
3. <input>
• <input> defines an input field.
• The attributes for this tag are type, name, value, checked, size, and
maxlength.
• The type attribute specifies the input type.
• Possible types are text for a one-line text field, radio for a radio
button, and checkbox for a check box.
• The name attribute gives a formal name for the attribute. This name
attribute is used by the servlet program to retrieve its associated
value.
• The names of the radio buttons in a group must be identical.
• The value attribute specifies a default value for a text field and text
area.
• The checked attribute indicates whether a radio button or a check
box is initially checked.
• The size attribute specifies the size of a text field, and the maxlength 82
attribute specifies the maximum length of a text field.
HTML tags to construct HTML forms
4. <select>
• <select> ... </select> defines a combo box or a list.
• The attributes for this tag are name, size, and multiple.
• The size attribute specifies the number of rows visible in the
list.
• The multiple attribute specifies that multiple values can be
selected from a list.
• Set size to 1 and do not use a multiple for a combo box.
83
HTML tags to construct HTML forms
5. <option>
• <option> ... </option> defines a selection list within a
<select> ... </select> tag.
• This tag may be used with the value attribute to specify a value
for the selected option (e.g., <option value = "CS">Computer
Science).
• If no value is specified, the selected option is the value.
6. <textarea>
• <textarea> ... </textarea> defines a text area.
• The attributes are name, rows, and cols.
• The rows and cols attributes specify the number of rows and
columns in a text area.
84
HTML Forms
<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h3>Student Registration Form</h3>
<form action = "GetParameters” method = "get">
<!-- Name text fields -->
<p><label>Last Name</label>
<input type = "text" name = "lastName" size = "20" />
<label>First Name</label>
<input type = "text" name = "firstName" size = "20" />
<label>MI</label>
<input type = "text" name = "mi" size = "1" /></p>
<!-- Gender radio buttons -->
<p><label>Gender:</label>
<input type = "radio" name = "gender" value = "M" checked /> Male
<input type = "radio" name = "gender" value = "F" /> Female</p>
<!-- Major combo box -->
<p><label>Major</label>
<select name = "major" size = "1">
<option value = "CS">Computer Science</option>
<option value = "Math">Mathematics</option>
<option>English</option>
<option>Chinese</option>
</select> 85
HTML Forms
Class.forName(dbDriver);
Connection con = DriverManager.getConnection(dbURL + dbName,
dbUsername,
dbPassword);
return con;
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Servlet Name
@WebServlet("/InsertData")
public class InsertData extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
try {
96