JDBC
JDBC
Standalone Applications
Web Applications
Mobile Applications
2
Different Editions of Java
3
J2EE Multi-tier Architecture
J2EE is a multi-tier architecture (four layered
architecture).
1. Client Tier:
1. Components of Client Tier will run in the client
devices / containers.
2. Client Tier components are standalone java
applications, static and dynamic HTML pages, and
applets.
2. Web Tier:
1. The web tier components namely JSP’s and Servlets
execute with the help of J2EE web server in a web
4
container.
J2EE Multi-tier Architecture
J2EE is a multi-tier architecture (four layered
architecture).
3. Business Logic Tier:
1. Enterprise Java Beans (EJB) are the business tier
components that are executed within the EJB
container using J2EE Application Server.
4. Database Tier:
1. In the Database tier, the application related data are
stored in a database.
5
J2EE Multi-tier Architecture
6
What is JDBC?
JDBC helps us to connect to a database and execute
SQL statements against a database.
JDBC API provides set of classes and interfaces with
different implementations respective to different
databases.
What’s an API?
“An API that lets you access virtually any tabular data
source from the Java programming language”
What’s a tabular data source?
“… access virtually any data source, from relational databases to
spreadsheets and flat files.”
7
General Architecture
8
JDBC Architecture
Oracle
Driver
Oracle
Java DB2
JDBC
Application Driver
DB2
Network
MySQL
Driver
We will
use this one… MySQL
9
What is JDBC Driver ?
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
19
1. Establish a connection
import java.sql.*;
Load the vendor specific driver
Class.forName("com.mysql.jdbc.Driver ");
What do you think this statement does, and how?
Dynamically loads a driver class, for MYSQL database
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Couldn't load the Driver");
} 20
1. Establish a connection
Make the connection
Connection con = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/ “+dbname,username,
passwd);
Establishes connection to database by obtaining
a Connection object
24
How to Execute SQL Commands
The Statement interface defines many execute methods:
Resultset rs =
statement.executeQuery("SELECT ...");
use for statements that return data values (SELECT)
Returns results as a ResultSet object
int count =
statement.executeUpdate("UPDATE ...");
Use for DROP TABLE, CREATE TABLE
use for INSERT, UPDATE, and DELETE
boolean b =
statement.execute("DROP TABLE test");
use to execute any SQL statement(s)
2. Create JDBC statement(s)
Creating the query
Obtain any of the Statement object in order to execute
the query.
Statement object can be either Statement,
PreparedStatement, or CallableStatement.
Use createStatement() method of Connection class to
create the simple Statement
26
2. Create JDBC statement(s) &
Executing SQL Statements
Executing the query
Once the statement is ready, Execute the SQL
query using executeQuery() method.
It returns a ResultSet object.
27
3. Executing SQL Statements
Statement st = null;
ResultSet rs = null;
String qry = "select * from stud";
try {
st = con.createStatement();
rs = st.executeQuery(qry);
}
catch (SQLException e) {
System.out.println("Error while processing SQL
query");
} 28
3. Executing SQL Statements
String createtab = "Create table stud " +
"(USN VARCHAR(10), Name VARCHAR(32), " +
"Marks Integer)";
stmt.executeUpdate(createtab);
stmt.executeUpdate(insertstud);
29
4. Get ResultSet
String querystud = "select * from stud";
ResultSet rs = Stmt.executeQuery(querystud);
while (rs.next()) {
String usn = rs.getString(“USN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
30
5. Close connection
Last step is to close the database connection.
This releases the external resources like cursor,
handlers etc.
try {
stmt.close();
pstmt.close();
rs.close();
con.close();
}
catch (Exception e) {
System.out.println("Error while closing the connection");
} 31
32
33
34
Statements in JDBC
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.
Example,
stmt = con.createStatement();
Statements in JDBC
There are three different kinds of statements:
Statement:
Used to implement simple SQL statements with no
parameters.
Statement st = null;
try {
st = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
Statement
Once you've created a Statement object, you can then use
it to execute a SQL statement with one of its three execute
methods.
40
JDBC Programs
41
JDBC Programs
42
JDBC Programs
43
JDBC Programs
44
PreparedStatement
The PreparedStatement is used to compile the query first
before executing it.
50
CallableStatement
CallableStatement object is used to execute a call to the
stored procedure from within a J2EE object.
2. OUT
3. INOUT
IN:
A parameter whose value is unknown when the SQL
statement is created.
You bind values to IN parameters with the setXXX()
methods.
CallableStatement
OUT:
A parameter whose value is supplied by the SQL
statement it returns.
You should register this parameter using
registerOutParameter() method.
You retrieve values from the OUT parameters with the
getXXX() methods.
INOUT:
A parameter that provides both input and output values.
You bind variables with the setXXX() methods and retrieve
values with the getXXX() methods.
CallableStatement
JDBC Programs
58
JDBC Programs INOUT Parameter
60
INOUT Parameter
61
ResultSet in JDBC
Types of ResultSet:
ResultSet.TYPE_FORWARD_ONLY
The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE
The cursor can scroll forwards and backwards.
Types of ResultSet:
ResultSet.TYPE_SCROLL_SENSITIVE
The cursor can scroll forwards and backwards.
ResultSet.CONCUR_READ_ONLY
Creates a read-only result set.
This is the default.
ResultSet.CONCUR_UPDATABLE
Creates an updateable result set.
72
Concurrency of ResultSet
Example 1:
Statement st = null;
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Example 2:
Statement st = null;
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)
73
Updating a ResultSet
rs = st.executeQuery(qry);
while (rs.next())
{
if (rs.getString("name").equals(“XYZ"))
{
rs.updateString("name", “ABCD");
rs.updateRow();
}
}
Updating a ResultSet
Deleting a Row
rs = st.executeQuery(qry);
while (rs.next())
{
if (rs.getString("name").equals(“PQR"))
{
rs.deleteRow();
}
}
Updating a ResultSet
Updating a ResultSet
Meta Data
80
DatabaseMetaData
Meta data is the data about the data.
81
DatabaseMetaData
Different methods in DatabaseMetaData interface:
Methods Information
getDatabaseProductName() Returns the product name of the
DBMS
getUserName() Returns the username
database
DatabaseMetaData
83
ResultSetMetaData
ResultSetMetaData interface describes the Result
set (virtual database).
getMetaData() method of the ResultSet object can
be used to retrieve the Result set metadata.
Commonly used methods in ResultSetMetaData
interface
Methods Information
getColumnCount() Returns the number of columns
obtained in the ResultSet
getColumnName(int number) Returns the name of the column
specified by the column number
getColumnType(int number) Returns the data type of the column 84
specified by the column number
ResultSetMetaData
85
Data Types
86
Handling Errors with Exceptions
There are three kinds of exceptions that are thrown
by JDBC methods.
SQLException
SQLWarning
DataTruncation
87
Handling Errors with Exceptions
SQLException:
It commonly reflects a syntax error in the query and is
thrown by many of the methods.
SQLWarning:
It throws warnings received by the connection from
the DBMS.
The getWarning() method of the Connection object
retrieves the warning and the getNextWarning()
method retrieves the subsequent warnings.
DataTruncation:
It is thrown whenever a data is lost due to the 88
truncation of the data value.
Handling Errors with Exceptions
89
Database Transaction
A Database Transaction consists of a set of SQL
statements, each of which must be successfully
completed for the transaction to be completed.
90
Database Transaction
Atomicity: Atomicity requires that each transaction is
"all or nothing": if one part of the transaction fails,
the entire transaction fails, and the database state is
left unchanged.
91
Database Transaction
Isolation: The isolation property ensures that the
concurrent execution of transactions results in a
system state that would be obtained if transactions
were executed serially, i.e. one after the other.
93
commit() and rollback() methods
The commit() method must be called regardless if
the SQL statement is part of a transaction or not.
94
commit() and rollback() methods
95
commit() and rollback() methods
96
Using Savepoints
A transaction may consist of many tasks, some of
which don't need to be rolled back when the
transaction fails.
The J2EE component can control the number of
tasks that are rolled back by using savepoints.
A savepoint is a virtual marker that defines the task
at which the rollback stops.
When you set a savepoint you define a logical
rollback point within a transaction.
If an error occurs past a savepoint, you can use the
rollback method to undo either all the changes or
only the changes made after the savepoint. 97
Using Savepoints
98
Using Savepoints
99
Batching SQL statements
Batch Processing allows you to group related SQL
statements into a batch and submit them with one
call to the database.
102
Batching SQL statements
103
Creating Table with Prepared Statement
104
Creating Table with Prepared Statement
105
Callable with Batch statements
106
Prepared Statement with Rollback
107
Creating mysql database, table
and inserting data
sql>show databases;
sql>create database mydb;
sql>use mydb;
sql>create table admin (username varchar(15),
password varchar(15),type varchar(5));
sql>show tables;
sql>insert into admin values
(‘aa1’,’Abc@123’,’user1’);
sql>commit;
sql>select * from admin; 108