0% found this document useful (0 votes)
2 views

Chapter 5 – Java Database Connectivity

Chapter 5 of the document provides an overview of Java Database Connectivity (JDBC), including its architecture, the JDBC API, and how to establish connections to databases using SQL. It outlines the basic steps for using a database in Java, such as creating statements, executing SQL commands, and processing results. The chapter also discusses the importance of JDBC in developing platform-independent database applications and includes sample code for practical implementation.

Uploaded by

nurahlee.dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 5 – Java Database Connectivity

Chapter 5 of the document provides an overview of Java Database Connectivity (JDBC), including its architecture, the JDBC API, and how to establish connections to databases using SQL. It outlines the basic steps for using a database in Java, such as creating statements, executing SQL commands, and processing results. The chapter also discusses the importance of JDBC in developing platform-independent database applications and includes sample code for practical implementation.

Uploaded by

nurahlee.dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

CSC584 Enterprise

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?

“… access virtually any data source, from relational


databases to spreadsheets and flat files.”

3
General Architecture

5
6
SQL
Structured Query Language, pronounced S-Q-L, or Sequel

 To access or write applications for database systems,


you need to use the Structured Query Language (SQL).
 SQL is the universal language for accessing relational
database systems.
 Application programs may allow users to access
database without directly using SQL, but these
applications themselves must use SQL to access the
database.

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

Create table insert into Course (courseId, subjectId, courseNumber, title)


Drop table values ('11113', 'CSCI', '3720', 'Database Systems', 3);
Describe
table
Select
Insert
Delete
Update

12
Examples of simple SQL statements

Create table update Course


Drop table set numOfCredits = 4
Describe where title = 'Database Systems';
table
Select
Insert
Update
Delete

13
Examples of simple SQL statements

Create table delete Course


Drop table where title = 'Database System';
Describe
table
Select
Insert
Update
Delete

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

Make the connection


◦ Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@oracle-prod:1521:OPROD",
username, passwd);
◦ What do you think this statement does?
◦ Establishes connection to database by obtaining
a Connection object
16
2. Create JDBC statement(s)
Statement stmt = con.createStatement() ;
Creates a Statement object for sending SQL statements to
the 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?

String insertLehigh = "Insert into Lehigh values“ +


"(123456789,abc,100)";
stmt.executeUpdate(insertLehigh);

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

Oracle JDBC JDBC-ODBC


Driver Bridge Driver

Oracle ODBC Microsoft


Driver ODBC Driver

Local or remote Microsoft Access


ORACLE DB Database

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");

Establishing A driver is a class. For example:


connections
Database Driver Class Source
Creating and
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
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'");

// Iterate through the result and print the student names


while (resultSet.next())
System.out.println(resultSet.getString(1) + "\t" +
resultSet.getString(2) + "\t" + resultSet.getString(3));

// Close the connection


connection.close();
}
}

29
Processing Statements

Once a connection to a particular database is established, it can be


used to send SQL statements from your program to the database.

JDBC provides the Statement, PreparedStatement, and


CallableStatement interfaces to facilitate sending statements to a
database for execution and receiving execution results from the
database.

30
Processing Statements Diagram

31
The execute, executeQuery, and
executeUpdate Methods

The methods for executing SQL statements are execute,


executeQuery, and executeUpdate, each of which accepts a string
containing a SQL statement as an argument.

This string is passed to the database for execution. The execute


method should be used if the execution produces multiple result
sets, multiple update counts, or a combination of result sets and
update counts.

32
The execute, executeQuery, and
executeUpdate Methods, cont.

The executeQuery method should be used if the execution


produces a single result set, such as the SQL select statement.

The executeUpdate method should be used if the statement


results in a single update count or no update count, such as a SQL
INSERT, DELETE, UPDATE, or DDL statement.

33
PreparedStatement

The PreparedStatement interface is designed to


execute dynamic SQL statements and SQL-stored
procedures with IN parameters. These SQL statements
and stored procedures are precompiled for efficient
use when repeatedly executed.
Statement pstmt = connection.prepareStatement
("insert into Student (firstName, mi, lastName) +
values (?, ?, ?)");
34
Handling Errors with Exceptions
Programs should recover and leave the database in a
consistent state.
If a statement in the try block throws an exception or
warning, it can be caught in one of the corresponding
catch statements
How might a finally {…} block be helpful here?
E.g., you could rollback your transaction in a
catch { …} block or close database connection and free
database related resources in finally {…} block

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

<b>Data Entry Menu</b>


<ul>
<li>
<a href="courses.jsp">Courses<a>
</li>
<li>
<a href="classes.jsp">Classes<a>
</li>
<li>
<a href="students.jsp">Students<a>
</li>
</ul>
Entry Form - First Attempt
JSP 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

<%-- Set the scripting language to java and --%>


<%-- import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>

<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());

// Make a connection to the Oracle datasource


Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@feast.ucsd.edu:1521:source",
“user", “pass");
%>
Entry Form - First Attempt
Statement Code

<%
// Create the statement
Statement statement = conn.createStatement();

// Use the statement to SELECT the student attributes


// FROM the Student table.
ResultSet rs = statement.executeQuery
("SELECT * FROM Student");
%>
Entry Form - First Attempt
Presentation Code

<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>

<%-- Get the ID --%>


<td><%= rs.getString("ID") %></td>

<%-- Get the FIRSTNAME --%>


<td><%= rs.getString("FIRSTNAME") %></td>

<%-- Get the LASTNAME --%>


<td><%= rs.getString("LASTNAME") %></td>

<%-- Get the COLLEGE --%>


<td><%= rs.getString("COLLEGE") %></td>
</tr>
Entry Form - First Attempt
Close Connectivity Code

<%
// Close the ResultSet
rs.close();

// Close the Statement


statement.close();

// Close the Connection


conn.close();

} catch (SQLException sqle) {


out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
%>
Entry Form - Second Attempt
Entry Form - Second Attempt
JSP Code

<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

// Check if an insertion is requested


String action = request.getParameter("action");
if (action != null && action.equals("insert")) {
conn.setAutoCommit(false);

// Create the prepared statement and use it to


// INSERT the student attrs INTO the Student table.
PreparedStatement pstmt = conn.prepareStatement(
("INSERT INTO Student VALUES (?, ?, ?, ?, ?)"));
pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN
")));
pstmt.setString(2, request.getParameter("ID"));

pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
Entry Form - Second 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 - 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

// Check if an update is requested


if (action != null && action.equals("update")) {

conn.setAutoCommit(false);

// Create the prepared statement and use it to


// UPDATE the student attributes in the Student table.
PreparedStatement pstatement = conn.prepareStatement(
"UPDATE Student SET ID = ?, FIRSTNAME = ?, " +
"LASTNAME = ?, COLLEGE = ? WHERE SSN = ?");

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

// Check if a delete is requested


if (action != null && action.equals("delete")) {

conn.setAutoCommit(false);

// Create the prepared statement and use it to


// DELETE the student FROM the Student table.
PreparedStatement pstmt = conn.prepareStatement(
"DELETE FROM Student WHERE SSN = ?");

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

(JNDI) Java Naming and Directory Interface


◦ API for network-wide sharing of information about users, machines,
networks, services, and applications
◦ Preserves Java’s object model
(JDO) Java Data Object
◦ Models persistence of objects, using RDBMS as repository
◦ Save, load objects from RDBMS
(SQLJ) Embedded SQL in Java
◦ Standardized and optimized by Sybase, Oracle and IBM
◦ Java extended with directives: # sql
◦ SQL routines can invoke Java methods
◦ Maps SQL types to Java classes

61
JDBC references

JDBC Data Access API – JDBC Technology Homepage


◦ http://java.sun.com/products/jdbc/index.html
JDBC Database Access – The Java Tutorial
◦ http://java.sun.com/docs/books/tutorial/jdbc/index.html
JDBC Documentation
◦ http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html
java.sql package
◦ http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html

JDBC Technology Guide: Getting Started


◦ http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html

JDBC API Tutorial and Reference (book)


◦ http://java.sun.com/docs/books/jdbc/

63
JDBC

JDBC Data Access API – JDBC Technology Homepage


◦ http://java.sun.com/products/jdbc/index.html
JDBC Database Access – The Java Tutorial
◦ http://java.sun.com/docs/books/tutorial/jdbc/index.html
JDBC Documentation
◦ http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html
java.sql package
◦ http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html

JDBC Technology Guide: Getting Started


◦ http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html

JDBC API Tutorial and Reference (book)


◦ http://java.sun.com/docs/books/jdbc/

64

You might also like