2. DATABASE BASED APPLICATION
Database is used to store data. It is also known as
persistent storage as the data is stored and can be
retrieved anytime. 2
3. INTRODUCTION
Database
Collection of data
DBMS
Database management system
Storing and organizing data
SQL
Relational database
Structured Query Language
CRUD operation in SQL
stands for create, read, update, delete.
7. STANDARD ACCESS TO DB
A
P
P
L
I
C
A
T
I
O
N
D
R
I
V
E
R
M
G
R
DBMS
Driver 1
DBMS
Driver 2
DBMS
Driver 3
DBMS 1
DBMS 2
DBMS 3
DB
DB
DB
8. OPEN DATABASE CONNECTIVITY
(ODBC) STANDARD
ODBC standard is an interface by which application
programs can access and process SQL databases in a
DBMS-independent manner. It contains:
A Data Source that is the database, its associated
DBMS, operating system and network platform
A DBMS Driver that is supplied by the DBMS vendor or
independent software companies
A Driver Manager that is supplied by the vendor of the
O/S platform where the application is running
10. ODBC INTERFACE
It is a system independent interface to database
environment that requires an ODBC driver to be
provided for each database system from which
you want to manipulate data.
The database driver bridges the differences
between your underlying system calls and the
ODBC interface functionality.
13. JAVA SUPPORT FOR ODBC : JDBC
When applications written in Java want to
access data sources, they use classes and
associated methods provided by Java DBC
(JDBC) API.
JDBC is specified as an “interface”.
An interface in Java can have many
“implementations”.
So it provides a convenient way to realize
many “drivers”
14. JDBC uses drivers to translate generalized JDBC
calls into vendor-specific database calls
Drivers exist for most popular databases
Four Classes of JDBC drivers exist
Type I
Type II
Type III
Type IV
JDBC
Drivers
15. Type I driver provides mapping between JDBC and access API of a database
The access API calls the native API of the database to establish communication
A common Type I driver defines a JDBC to ODBC bridge
ODBC is the database connectivity for databases
JDBC driver translates JDBC calls to corresponding ODBC calls
Thus if ODBC driver exists for a database this bridge can be used to
communicate with the database from a Java application
Inefficient and narrow solution
Inefficient, because it goes through multiple layers
Narrow, since functionality of JDBC code limited to whatever ODBC supports
JDBC
Drivers (Type I)
Client
Application
ODBC
API
Database
Driver
(Type
I)
Native
API Database Specific
Protocol
API Protocol
16. Type II driver communicates directly with native API
Type II makes calls directly to the native API calls
More efficient since there is one less layer to contend with
(i.e. no ODBC)
It is dependent on the existence of a native API for a
database
JDBC
Drivers (Type II)
Client
Application Database
Driver
(Type
II)
Native
API
Database Specific
Protocol
API Protocol
17. Type III driver make calls to a middleware component running on
another server
This communication uses a database independent net protocol
Middleware server then makes calls to the database using database-
specific protocol
The program sends JDBC call through the JDBC driver to the middle
tier
Middle-tier may use Type I or II JDBC driver to communicate with the
database.
JDBC
Drivers (Type III)
Database
Client
Application
Driver
(Type
III)
Middleware
Server
Net Protocol Database Specific
Protocol
18. Type IV driver is an all-Java driver that is also called a thin
driver
It issues requests directly to the database using its native protocol
It can be used directly on platform with a JVM
Most efficient since requests only go through one layer
Simplest to deploy since no additional libraries or middle-ware
JDBC
Drivers (Type IV)
Database
Client
Application
Driver
(Type
IV)
Database Specific
Protocol
19. JDBC ARCHITECTURE (CONT.)
Application JDBC Driver
Java code calls JDBC library
JDBC loads a driver
Driver talks to a particular database
An application can work with several databases by using all
corresponding drivers
20. JAVA SUPPORT FOR SQL
Java supports embedded SQL.
Also it provides an JDBC API as a standard way
to connect to common relational databases.
Java.sql package and an extensive exception
hierarchy.
21. DATA SOURCE AND DRIVER
Data source is the data base created using any
of the common database applications available.
Your system should have the driver for the
database you will be using.
For example your Windows system should have
the MS Access Driver.
There are a number of JDBC drivers available.
Information on installing them is available at :
http://industry.java.sun.com/products/jdbc/drivers
22. JDBC COMPONENTS
Driver Manager: Loads database drivers, and manages
the connection between application & driver.
Driver: Translates API calls to operations for a specific
data source.
Connection: A session between an application and a
driver.
Statement: A SQL statement to perform a query or an
update operation.
Metadata: Information about the returned data, driver
and the database.
Result Set : Logical set of columns and rows returned by
executing a statement.
23. JDBC CLASSES
Java supports DB facilities by providing classes and
interfaces for its components
DriverManager class
Connection interface
Statement interface (to be instantiated with values from
the actual SQL statement)
ResultSet interface
24. JDBC PROGRAMMING STEPS
1. Import necessary packages; Ex: import java.sql.*;
2. Load JDBC driver(driver should have been installed)
3. Data source and its location should have been
registered.
4. Allocate Connection object, Statement or
PreparedStatement object and ResultSet object
5. Execute query using Statement or
PreparedStatement object
6. Retrieve data from ResultSet object
7. Close Connection object.
25. BASIC SELECT QUERY
Simplest format of a SELECT query
SELECT * FROM tableName
SELECT * FROM authors
Select specific fields from a table
SELECT authorID, lastName FROM authors
authorID lastName
1 Deitel
2 Deitel
3 Nieto
4 Santry
Fig. 8.13 authorID and lastName from the authors table.
26. WHERE CLAUSE
specify the selection criteria
SELECT fieldName1, fieldName2, … FROM tableName WHERE
criteria
SELECT title, editionNumber, copyright
FROM titles
WHERE copyright > 1999
WHERE clause condition operators
<, >, <=, >=, =, <>
27. INSERT INTO STATEMENT
Insert a new record into a table
INSERT INTO tableName ( fieldName1, … ,
fieldNameN )
VALUES ( value1, … , valueN )
INSERT INTO authors ( firstName, lastName )
VALUES ( ‘Sue’, ‘Smith’ )
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
5 Sue Smith
Fig. 8.22 T
able Authors after an INSERT INTO operation to add a rec ord.
28. UPDATE STATEMENT
Modify data in a table
UPDATE tableName
SET fieldName1 = value1, … , fieldNameN =
valueN
WHERE criteria
UPDATE authors
SET lastName = ‘Jones’
WHERE lastName = ‘Smith’ AND firstName
= ‘Sue’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
5 Sue Jones
Fig. 8.23 T
able authors after an UPDATE operation to c hange a rec ord.
29. DELETE FROM STATEMENT
Remove data from a table
DELETE FROM tableName WHERE criteria
DELETE FROM authors
WHERE lastName = ‘Jones’ AND
firstName = ‘Sue’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
Fig. 8.24 T
able authors after a DELETE operation to remove a rec ord.
32. STEP 1: LOAD THE DRIVER
Loading drivers – An appropriate driver must be loaded
using the statement shown below before connecting to
a databases
33
33. STEP 2:DEFINE THE CONNECTION URL
To connect to a database, use the static method
getConnection(databaseURL) :
e.g. Connection conn1 = DriverManager.getConnection
(databaseURL);
34
34. EXAMPLE 1
public static final String DB_NAME ="registration.db";
public static final String CONNECTION_STRING = "jdbc:
sqlite: D:databases"+DB_NAME;
Connection conn1 =
DriverManager.getConnection(CONNECTION_STRIN
G);
35
36. STEP 3: ESTABLISH THE CONNECTION
The following statement creates a Connection
object:
Connection conn1;
conn1 = DriverManager.getConnection(url);
37
37. STEP 4: CRATING STATEMENT OR PREPARED
STATEMENT
Statement and PreparedStatement interface defines the
methods and properties that enable you to send SQL
commands and receive data from your database.
Once a Connection object is created, you can create
statements for executing SQL statements as follows:
Statement st = conn1.createStatement();
PreparedStatement ps= conn1.prepareStatement();
38
38. METHODS OF STATEMENT INTERFACE
boolean execute (String SQL): Returns a boolean value of true if
a ResultSet object can be retrieved; otherwise, it returns false.
Use this method to execute SQL DDL statements
int executeUpdate (String SQL): Returns the number of rows
affected by the execution of the SQL statement.
Use this method to execute SQL statements for which you expect
to get a number of rows affected.
- for example, an INSERT, UPDATE, or DELETE statement.
ResultSet executeQuery (String SQL): Returns a ResultSet
object. Use this method when you expect to get a result set, as
you would with a SELECT statement.
39
39. STEP 5: EXECUTE A QUERY USING THE
STATEMENT
An SQL query statement can be executed using
String queryCheck = "SELECT * from login";
rs = st.executeQuery(queryCheck);
An SQL update statement can be executed using
executeUpdate(String sql),
Example:
st.executeUpdate("INSERT INTO authors ( firstName,
lastName ) VALUES ( 'Sue', 'Smith' )" );
40
40. RESULTSET
The SELECT statement is the standard way to
select rows from a database and view them in a
result set.
The java.sql.ResultSet interface represents the
result set of a database query.
A ResultSet object maintains a cursor that points to
the current row in the result set.
The term "result set" refers to the row and column
data contained in a ResultSet object.
41
41. RESULTSET
ResultSet objects provide access to the tables generated as
results of executing a Statement queries
Only one ResultSet per Statement can be open at the same
time!
The table rows are retrieved in sequence
A ResultSet maintains a cursor pointing to its current row
The next() method moves the cursor to the next row
42. RESULTSET METHODS
boolean next()
activates the next row
the first call to next() activates the first row
returns false if there are no more rows
Type getType(int columnIndex)
returns the given field as the given type
indices start at 1 and not 0
Type getType(String columnName)
same, but uses name of field
int findColumn(String columnName)
looks up column index given column name
43. STEP 6: PROCESSING RESULT
The result of the query is returned in ResultSet,
Example:
ResultSet rs = st.executeQuery(queryCheck);
Eg:
rs = st.executeQuery(queryCheck);
while(rs.next()){
s=rs.getString("login_name");
System.out.println("login= "+s);
p=rs.getString("password");
System.out.println("password= "+p);
}
44
45. ABOUT PREPARED STATEMENTS
Extends functionality of Statement interface
Gives the flexibility of supplying arguments dynamically.
They are parsed (compiled) by the DBMS only once
Column values can be set after compilation
Instead of values, use ‘?’
The setXXX() methods bind values to the parameters,
where XXX represents the Java data type of the value
you wish to bind to the input parameter.
46. STEP 5: EXECUTE A QUERY USING THE
PREPAREDSTATEMENT
Can execute query using execute(), executeQuery()
and executeUpdate()
Example:
ps.executeUpdate("update customer set acctype=?
where cname=?" );
47
48. 49
STEP 7:CLEANING UP AFTER YOURSELF
Remember to close the Connections, Statements, Prepared
Statements and Result Sets
con.close();
stmt.close();
rs.close()
49. SELECT QUERY
ID fname lname
1 John Smith
2 Paul Dietel
3 Tem Neito
50
ResultSet rs= st.executeQuery(“SELECT *FROM employee”);
while(rs.next()){
int id= rs.getInt(1);
String f_name = rs.getString(“fname”);
String l_name = rs. getString(“lname”);
}
Table: employee
50. SELECT QUERY
ID fname lname
1 John Smith
2 Paul Dietel
3 Tem Neito
51
String selectquery = “SELECT *FROM employee WHERE
lname=?”;
PreparedStatement ps = con.prepareStatement(selectquery) ;
ps.setSting(1, “Smith”);
ResultSet rs= ps.executeQuery();
while(rs.next()){
int id= rs.getInt(1);
String f_name = rs.getString(“fname”);
String l_name = rs. getString(“lname”);
}
53. DELETE QUERY
String deleteQuery = "DELETE FROM employee WHERE
fname = ?";
PreparedStatement ps =
con.prepareStatement(deleteQuery);
ps.setString(1,”John”);
int result = ps.executeUpdate();
System.out.println(result + “Row deleted”);
54
54. MAPPING JAVA TYPES TO SQL TYPES
SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
55. SUMMARY
JDBC allows you to write Java programs that
manipulate a database
A driver (often a separate product) is required that
facilitates access
Key classes: Connection, Statement,
PreparedStatement, and ResultSet