Chapter 5 – Java Database Connectivity
Chapter 5 – Java Database Connectivity
Programming
Chapter 5 – Java Database connectivity
MARSHIMA MOHD ROSLI
COMPUTER SCIENCE
Java Database connectivity
Overview of java database programming
Define JDBC API
Chapter 5 Describe various types of JDBC
Outline Identify JDBC product
Describe the 2 tier server client model
Setup JDBC connection to a database with
JSP and Servlet
Create and Execute SQL statement
Describe ResultSet Object
What is JDBC?
“An API that lets you access virtually any tabular data source
from the Java programming language”
◦ What’s an API?
◦ What’s a tabular data source?
3
General Architecture
5
6
SQL
Structured Query Language, pronounced S-Q-L, or Sequel
7
Examples of simple SQL statements
create table Course ( create table Student (
Create table courseId char(5), ssn char(9),
Drop table subjectId char(4) not null, firstName varchar(25),
Describe mi char(1),
courseNumber integer, lastName varchar(25),
table
title varchar(50) not null, birthDate date,
Select
numOfCredits integer, street varchar(25),
Insert phone char(11),
primary key (courseId)
Delete zipCode char(5),
);
Update deptId char(4),
primary key (ssn)
);
8
Examples of simple SQL statements
Create table drop table Enrollment;
Drop table drop table Course;
Describe drop table Student;
table
Select
Insert
Delete
Update
9
Examples of simple SQL statements
Create table describe Course; -- Oracle
Drop table
Describe
table
Select
Insert
Delete
Update
10
Examples of simple SQL statements
Create table select firstName, mi, lastName
Drop table from Student
Describe where deptId = 'CS';
table
Select select firstName, mi, lastName
Insert from Student
Delete where deptId = 'CS' and zipCode = '31411';
Update
select *
from Student
where deptId = 'CS' and zipCode = '31411';
11
Examples of simple SQL statements
12
Examples of simple SQL statements
13
Examples of simple SQL statements
14
Basic steps to use
a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
15
1. Establish a connection
import java.sql.*;
Load the vendor specific driver
◦ Class.forName("oracle.jdbc.driver.OracleDriver");
◦ What do you think this statement does, and how?
◦ Dynamically loads a driver class, for Oracle database
17
Executing SQL Statements
String createLehigh = "Create table Lehigh " +
"(SSN Integer not null, Name VARCHAR(32), " +
"Marks Integer)";
stmt.executeUpdate(createLehigh);
//What does this statement do?
18
Get ResultSet
String queryLehigh = "select * from Lehigh";
ResultSet rs = Stmt.executeQuery(queryLehigh);
//What does this statement do?
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
19
Close connection
stmt.close();
con.close();
20
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.
Third, Java is taught in almost every university either as the first
programming language or as the second programming language.
21
Database Applications Using Java
GUI
Client/Server
Server-Side programming
22
The Architecture of JDBC
Java Applications/
Applets
JDBC API
23
The JDBC Interfaces
Driver Loading drivers
Establishing
Connection Connection connections
Creating and
Statement Statement Statement Statement executing
statements
Processing
ResultSet ResultSet ResultSet ResultSet ResultSet
24
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 classpath using the following DOS command on
Windows:
classpath=%classpath%;c:\book\mysqljdbc.jar;c:\book\classes12.jar
25
Developing JDBC Programs
Connection connection = DriverManager.getConnection(databaseURL);
Loading 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: See Supplement IV.D for
For Access: creating an ODBC data source
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");
26
Developing JDBC Programs
Loading drivers Creating statement:
Statement statement = connection.createStatement();
Establishing
connections
Executing statement (for update, delete, insert):
Creating and statement.executeUpdate
executing ("create table Temp (col1 char(5), col2 char(5))");
statements
Executing statement (for select):
Processing // Select the columns from the Student table
ResultSet ResultSet resultSet = statement.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
27
Developing JDBC Programs
Loading drivers Executing statement (for select):
// Select the columns from the Student table
Establishing ResultSet resultSet = stmt.executeQuery
connections ("select firstName, mi, lastName from Student where lastName "
+ " = '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));
28
import java.sql.*;
public class SimpleJdbc {
public static void main(String[] args)
throws SQLException, ClassNotFoundException {
Simple
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
JDBC
System.out.println("Driver loaded"); Example
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select firstName, mi, lastName from Student where lastName
"
+ " = 'Smith'");
29
Processing Statements
30
Processing Statements Diagram
31
The execute, executeQuery, and
executeUpdate Methods
32
The execute, executeQuery, and
executeUpdate Methods, cont.
33
PreparedStatement
35
Sample program
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic loading of driver
String filename = "c:/db1.mdb"; //Location of an Access database
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; //add on to end
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute("create table TEST12345 ( firstcolumn integer )");
s.execute("insert into TEST12345 values(1)");
s.execute("select firstcolumn from TEST12345"); 36
Sample program(cont)
ResultSet rs = s.getResultSet();
if (rs != null) // if rs == null, then there is no ResultSet to view
while ( rs.next() ) // this will step through our data row-by-row
{ /* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("Data from column_name: " + rs.getString(1) );
}
s.close(); // close Statement to let the database know we're done with it
con.close(); //close connection
}
catch (Exception err) { System.out.println("ERROR: " + err); }
}
} 37
Activity 1
JDBC exercise
- Fill in the blanks
Example: JDBC with JSP
JSP Syntax
Comment
◦ <%-- Comment --%>
Expression
◦ <%= java expression %>
Scriplet
◦ <% java code fragment %>
Include
◦ <jsp:include page="relativeURL" />
Entry Form - First Attempt
Entry Form - First Attempt
Menu HTML Code
<html>
<body>
<table>
<tr>
<td>
<jsp:include page="menu.html" />
</td>
<td>
Open connection code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
Entry Form - First Attempt
Open Connectivity Code
<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
<%
// Create the statement
Statement statement = conn.createStatement();
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Entry Form - First Attempt
Entry Form - First Attempt
Iteration Code
<tr>
<%-- Get the SSN, which is a number --%>
<td><%= rs.getInt("SSN") %></td>
<%
// Close the ResultSet
rs.close();
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
Entry Form - Second Attempt
Insertion Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Entry Form - Second Attempt
Insert Form Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="insert" name="action">
<th><input value="" name="SSN" size="10"></th>
<th><input value="" name="ID" size="10"></th>
<th><input value="" name="FIRSTNAME" size="15"></th>
<th><input value="" name="LASTNAME" size="15"></th>
<th><input value="" name="COLLEGE" size="15"></th>
<th><input type="submit" value="Insert"></th>
</form>
</tr>
Entry Form - Third Attempt
Entry Form - Third Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Update Code
Delete Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
Entry Form - Third Attempt
Update Code
conn.setAutoCommit(false);
pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));
…
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Entry Form - Third Attempt
Delete Code
conn.setAutoCommit(false);
pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));
int rowCount = pstmt.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Entry Form - Third Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Entry Form - Third Attempt
Iteration Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="update" name="action">
<td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td>
<td><input value="<%= rs.getString("ID") %>" name="ID"></td>
…
<td><input type="submit" value="Update"></td>
</form>
<form action="students2.jsp" method="get">
<input type="hidden" value="delete" name="action">
<input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN">
<td><input type="submit" value="Delete"></td>
</form>
</tr>
JDBC and beyond
61
JDBC references
63
JDBC
64