Unit3 JDBC
Unit3 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
2. Web tier
3. Business logic tier
4. Database tier
4
J2EE Multi-tier Architecture
5
What is JDBC?
JDBC helps us to connect to a database and execute
SQL statements against a database. JDBC API provides
set of interfaces and there are 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.”
6
General Architecture
7
JDBC Architecture
Oracle
Driver
Oracle
Java DB2
JDBC
Application Driver
DB2
Network
MySQL
Driver
We will
use this one… MySQL
8
What is JDBC Driver ?
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
18
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");
} 19
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
23
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
25
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.
26
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");
} 27
3. Executing SQL Statements
String createtab = "Create table stud " +
"(USN VARCHAR(10), Name VARCHAR(32), " +
"Marks Integer)";
stmt.executeUpdate(createtab);
stmt.executeUpdate(insertstud);
28
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");
}
29
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");
} 30
31
32
33
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.
39
JDBC Programs
40
JDBC Programs
41
JDBC Programs
42
JDBC Programs
43
PreparedStatement
The PreparedStatement is used to compile the query first
before executing it.
49
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
57
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.
65
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)
66
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
73
DatabaseMetaData
Meta data is the data about the data.
74
DatabaseMetaData
Different methods in DatabaseMetaData interface:
Methods Information
getDatabaseProductName() Returns the product name of the
DBMS
getUserName() Returns the username
database
DatabaseMetaData
76
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 77
specified by the column number
ResultSetMetaData
78
Data Types
79
Handling Errors with Exceptions
There are three kinds of exceptions that are thrown
by JDBC methods.
SQLException
SQLWarning
DataTruncation
80
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 81
truncation of the data value.
Handling Errors with Exceptions
82
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.
83
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.
84
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.
86
commit() and rollback() methods
The commit() method must be called regardless if
the SQL statement is part of a transaction or not.
87
commit() and rollback() methods
88
commit() and rollback() methods
89
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. 90
Using Savepoints
91
Using Savepoints
92
Batching SQL statements
Batch Processing allows you to group related SQL
statements into a batch and submit them with one
call to the database.
95
Batching SQL statements
96
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; 97
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; 98