2. Contents
0 Overview
0 History of JDBC
0 JDBC Model
0 JDBC Driver Type
0 JDBC Programming Steps
0 Step 1 : Loading a JDBC Driver
0 Step 2 : Connecting to a Database
0 Step 3 : Executing SQL
0 Step 4 : Processing the Results
0 Step 5 : Closing Database Connection
0 The PreparedStatement Object
0 Transaction and JDBC
0 Summary
0 Online Resources
Adv. Prog : JDBC 2
3. Overview
0 JDBC stands for Java Database Connectivity, which is a standard Java
API for database-independent connectivity between the Java
programming language and a wide range of databases.
0 The JDBC library includes APIs for each of the tasks commonly
associated with database usage:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
Adv. Prog : JDBC 3
4. Overview(cont)
0 Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database.
Java can be used to write different types of executables, such as:
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs)
0 All of these different executables are able to use a JDBC driver to access
a database and take advantage of the stored data.
0 JDBC provides the same capabilities as ODBC, allowing Java programs to
contain database-independent code.
Adv. Prog : JDBC 4
5. Overview(cont)
0 JDBC
0 JDBC is a standard interface for connecting to relational databases
from Java
0 The JDBC Classes and Interfaces are in the java.sql package
0 JDBC is Java API for executing SQL statements
0Provides a standard API for tool/database developers
0Possible to write database applications using a pure Java API
0Easy to send SQL statements to virtually any relational database
0 What does JDBC do?
0 Establish a connection with a database
0 Send SQL statements
0 Process the results
Adv. Prog : JDBC 5
JDBC Driver
JAVA Applet/
Application Database
JDBC Call
Database
Command
6. Overview (cont)
0 Reason for JDBC
0 Database vendors (Microsoft Access, Oracle etc.) provide
proprietary (non standard) API for sending SQL to the server
and receiving results from it
0 Languages such as C/C++ can make use of these proprietary
APIs directly
0High performance
0Can make use of non standard features of the database
0All the database code needs to be rewritten if you change
database vendor or product
0 JDBC is a vendor independent API for accessing relational
data from different database vendors in a consistent way
Adv. Prog : JDBC 6
CCTM: Course material developed by James King (james.king@londonmet.ac.uk)
7. History of JDBC
0 JDBC 1.0 released 9/1996.
0 Contains basic functionality to connect to database, query database,
process results
0 JDBC classes are part of java.sql package
0 Comes with JDK 1.1
0 JDBC 2.0 released 5/1998
0 Comes with JDK 1.2
0 javax.sql contains additional functionality
0 Additional functionality:
0Scroll in result set or move to specific row
0Update database tables using Java methods instead of SQL
commands
0Send multiple SQL statements to the database as a batch
0Use of SQL3 datatypes as column values
Adv. Prog : JDBC 7
8. History of JDBC (cont)
0 JDBC 3.0 released 2/2002
0 Comes with Java 2, J2SE 1.4
0 Support for:
0 Connection pooling
0 Multiple result sets
0 Prepared statement pooling
0Save points in transactions
Adv. Prog : JDBC 8
9. History of JDBC (cont)
Adv. Prog : JDBC 9
JDBC Version
Bundled
with
Package
Name
Contents
JDBC 1.0 (previously
called 1.2)
JDK 1.1 java.sql Basic Java client to database connectivity.
JDBC 2.0 core API
JDK 1.2
and later
java.sql
Added features such as scrollable result sets,
batch updates, new data types for SQL-3, and
programmable updates using the result set.
JDBC 2.0 optional API
J2EE and
later
javax.sql
Can be downloaded from
www.java.sun.com/products/jdbc/ . Contains
database server-side functionality. Prepares the
ground for the use of database-aware Java beans.
JDBC 2.1 optional API
Not
bundled
javax.sql
Incremental improvement and additions over the
2.0 API.
JDBC 3.0 core API
JDK 1.4
and later
java.sql
Adds support for connection pooling, statement
pooling, and a migration path to the Connector
Architecture.
10. JDBC Model
0 JDBC consists of two parts:
0 JDBC API, a purely Java-based API
0 JDBC driver manager
Communicates with vendor-specific drivers
0NB: translation to vendor
format is performed on
the client
No changes needed
to server
Driver (translator) needed
on client
Adv. Prog : JDBC 10
JAVA Applet/
Application
JDBC API
Driver Manager
Driver API
Vendor Specific
JDBC Driver
JDBC-ODBC Bridge
Database
Vender Specific
ODBC Driver
Database
Java Application
Developer
JDBC Developer
Vender Specific JDBC
developer
11. JDBC Model(cont)
Adv. Prog : JDBC 11
Java
Application JDBC
Oracle
DB2
MySQL
Oracle
Driver
DB2
Driver
MySQL
Driver
Network
We will
use this one…
12. JDBC Model(cont)
0Java code calls JDBC library
0JDBC loads a driver
0Driver talks to a particular database
0An application can work with several databases by using
all corresponding drivers
0Ideal: can change database engines without changing any
application code (not always in practice)
Adv. Prog : JDBC 12
Application JDBC Driver
13. Connecting To A Database
0 A database works in the classic client/server fashion.
There is one database and many clients talk to it. (Larger
applications may have multiple databases, but they can
be considered independently for our purposes.)
0 In a 2-tier system, the clients talk directly to the database
while in a 3-tier system, the clients talk to a business logic
server which in turn talks to the database. The business
logic server would also contain server-side JDBC
functionality.
Adv. Prog : JDBC 13
14. Connecting To A Database (cont.)
0 A JDBC driver is typically available from the database
vendor of the database to which you wish to connect.
0 There are several different kinds of drivers depending on
whether it was written in Java or native code, or whether
it talks directly to the database or through another
database access protocol (such as Microsoft’s ODBC).
From an application programmer’s point of view, none of
this matters very much as long as you have a working
JDBC driver.
0 JDBC supports four categories of drivers which are
detailed in the table on the next slide.
Adv. Prog : JDBC 14
15. JDBC Driver Types
0 JDBC drivers implement the defined interfaces in the JDBC API
for interacting with your database server.
0 For example, using JDBC drivers enable you to open database
connections and to interact with it by sending SQL or database
commands then receiving results with Java.
0 The Java.sql package that ships with JDK contains various
classes with their behaviours defined and their actual
implementaions are done in third-party drivers. Third party
vendors implements the java.sql.Driver interface in their
database driver.
Adv. Prog : JDBC 15
16. JDBC Driver Types(cont)
Type Description
1
JDBC-to-ODBC Bridge Driver – connects Java to a Microsoft ODBC (Open
Database Connectivity) data source. This driver requires the ODBC driver to
be installed on the client computer and configuration of the ODBC data
source. This driver is used to allow Java programmers to build data-driver
Java applications before the database vendor supplies a Type 3 or Type 4
driver. In general, this will not be used too much these days.
2
Native-API, Part Java Drivers – enable JDBC programs to use database-
specific APIs (normally written in C or C++) that allow client programs to
access databases via the Java Native Interface. This driver translates JDBC
into database-specific code. Reasons for use are similar to Type 1.
3
JDBC-Net Pure Java Drivers – take JDBC requests and translate them into
a network protocol that is not database specific. These requests are sent to
a server, which translates the database requests into a database-specific
protocol.
4
Native-protocol Pure Java Drivers – convert JDBC requests to database-
specific network protocols, so that Java programs can connect directly to a
database.
17. JDBC Driver Types(cont)
Which Driver should be used?
0 If you are accessing one type of database, such as Oracle, Sybase, or
IBM, the preferred driver type is 4.
0 If your Java application is accessing multiple types of databases at
the same time, type 3 is the preferred driver.
0 Type 2 drivers are useful in situations where a type 3 or type 4 driver
is not available yet for your database.
0 The type 1 driver is not considered a deployment-level driver and is
typically used for development and testing purposes only.
Adv. Prog : JDBC 17
18. Some Popular JDBC Drivers
RDBMS JDBC Driver Name
MySQL
Driver Name : com.mysql.jdbc.Driver
Database URL format:
jdbc:mysql//hostname/databaseName
Oracle
Driver Name : oracle.jdbc.driver.OracleDriver
Database URL format:
jdbc:oracle:thin@hostname:portnumber:databaseName
DB2
Driver Name : com.ibm.db2.jdbc.net.DB2Driver
Database URL format:
jdbc:db2:hostname:portnumber/databaseName
Access
Driver Name : com.jdbc.odbc.JdbcOdbcDriver
Database URL format:
jdbc:odbc:databaseName
Java DB
Driver Name : com.org.derby.jdbc.ClintDriver
Database URL format:
jdbc:derby:databaseName
19. Java application
java.sql.DriverManager
java.sql.package
(JDBC library)
Driver for MySQL
databases
Driver for Oracle
databases
MySQL
DB
1. Application
causes driver to be
loaded
2. Application asks DriverManager
for a connection to a particular DB.
DriverManager asks all loaded
drivers, and one of them responds
with a connection.
3. DriverManager
gives connection
to the application.
4. Connection
supplied by
DriverManager is
used by
application to talk
JDBC through
the driver to the
database.
How JDBC establishes a
connection between your
code and a database
20. JDBC Programming Steps
Adv. Prog : JDBC 20
Connect
Query
Process Results
Close
1) Register the driver
2) Create a connection to the database
1) Create a statement
2) Query the database
1) Get a result set
2) Assign results to Java variables
1) Close the result set
2) Close the statement
3) Close the connection
21. Primary JDBC classes
0 Java classes used for JDBC
0 DriverManager: used to load the class which is the driver
for a specific database.
0 Connection: the database connection interface.
0 Statement: An SQL statement to be executed on the
connection.
0 ResultSet: The set of results that are returned by a query.
0If supported by the driver, the result set can be updated and
saved back to the data base as necessary.
0 The DataSource interface can be used for any object that can
be used as a database connection.
Adv. Prog : JDBC 21
22. Let’s Do this:
0 Create a database called StudentDB.
0 Create a table called StudentInfo which has only two
columns Id and Name.
0 After this we want to insert students’ information to
this StudetnInfo table from the java application.
0 And we want to fetch students’ information from
StudetnInfo table and display them onto the consol.
Adv. Prog : JDBC 22
23. Task One: Creating the DB
0 First open the services window like this
Adv. Prog : JDBC 23
Click on Windows->
Services.
24. Task One: Creating the DB
0 Now start the Apache Derby Network Server and create database called
StudentDB
Adv. Prog : JDBC 24
25. Task One: Creating the DB
0 Create the database like this by giving the password “student” then press ok
Adv. Prog : JDBC 25
26. Task One: Creating the DB
0 The database and the database connection will be created. Then connect the
database connection like this.
Adv. Prog : JDBC 26
27. Task One: Creating the DB
0 When you connect the database connection then many schemas will be
visible. Now click on Excecute Command… to create a table into the default
schema STUDENT which is bolded by default.
Adv. Prog : JDBC 27
28. Task One: Creating the DB
0 Now write a SQL statement to create a table called StudentInfo which has
two columns called Id and Name and then click on Run SQL. Then you will
see the excution is correct in the excution toolbar. If it is correctly executed,
you can see the table that you have created in the default schema.
Adv. Prog : JDBC 28
29. Task One: Creating the DB
0 Now you can see the table in the default schema.
Adv. Prog : JDBC 29
30. Task Two : Adding a Driver
0 Normally, the driver is provided by the database vendor, and is specific to a
particular database and version.
0 The file needs to be on the class path.
0 For Derby that we’ll going to use for our examples:
0 Driver class is in the derbyclient.jar file, and this archive must be on
the class path.
0 You can download the driver derbyclient.jar file from the internet and
add it to your project like this. The latest derbyclient version now is
derbyclient-10.1.2.1.
0 Assume I have downloaded the jar file in my “LibrariesMy Documents”.
0 So this is the way that I will add the jar file.
Adv. Prog : JDBC 30
31. Task Two : Adding a Driver
0 Let’s create a project called StudentDerbyDemo then right click on the
project -> properties->select “Library” -> click on “Add jar/Folder” button->
then select the jar file->ok.
Adv. Prog : JDBC 31
32. Task Three:
Setting up the JDBC connection
Step 1: Load the appropriate driver class.
0 A JDBC driver is needed to connect to a database
0 Loading a driver requires the class name of the driver.
Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver
Oracle driver: oracle.jdbc.driver.OracleDriver
MySQL: com.mysql.jdbc.Driver
Java DB : org.apache.derby.jdbc.ClientDriver
0 Loading the driver class
Class.forName("DriverName");
0 It is possible to load several drivers.
0 The class DriverManager manages the loaded driver(s)
Adv. Prog : JDBC 32
33. Task Three:
Setting up the JDBC connection
Step 1: Load the appropriate driver class.
0 Normally, the driver is provided by the database vendor, and is specific to a
particular database and version.
0 The class needs to be on the class path.
0 For Derby that we’ll going to use for our example:
0 Driver class is in the derbyclient.jar file, and this archive must be on
the class path.
0 Class name is org.apache.derby.jdbc.ClientDriver
0 To load the driver in Java, include the following statements:
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName( driver );
or
Driver myDriver = new org.apache.derby.jdbc.ClientDriver( );
DriverManager.registerDriver(myDriver);
Adv. Prog : JDBC 33
34. Step 2: Setup the URL for the database:
0 format:
jdbc:db_vendor://host:port/location
0 For Derby, running as a client on the same computer using the default Derby
port, the first part is:
jdbc:derby://localhost:1527/location
0 The location can be specified exactly as a folder name:
jdbc:derby://localhost:1527/C:DerbyDatabasesseg3203
0 A default database location folder is also set by the Derby server. Locations
relative to that folder can be specified directly:
jdbc:derby://localhost:1527/seg3203
0 So for our StudentDB, it will be like this.
String url = "jdbc:derby://localhost:1527/StudentDB“;
Adv. Prog : JDBC 34
Task Three:
Setting up the JDBC connection
35. Task Three:
Setting up the JDBC connection
Step 3: Connect to the database.
0 Ask the DriverManager for a connection.
Connection connection;
connection = DriverManager.getConnection(url,
username, password );
Adv. Prog : JDBC 35
36. Task Three:
Setting up the JDBC connection
Step 4: Create a statement from the connection.
0 Statement object
0 Can be obtained from a Connection object
0 Sends SQL to the database to be executed
0 Statement has three methods to execute a SQL statement:
0 executeQuery() for QUERY statements
0 Returns a ResultSet which contains the query results
0 executeUpdate() for INSERT, UPDATE or DELETE statements
0 Returns an integer, the number of affected rows from the SQL
0 execute() for either type of statement
0 You need to create a statement to execute queries.
Statement stmt;
stmt = connection.createStatement();
Adv. Prog : JDBC 36
37. Task Three:
Setting up the JDBC connection
Step 4: Create a statement from the connection.
0 Insertion
String insertQuery;
insertQuery = "insert into StudentsInfo values(1,‘Kebede')";
stmt.execute(insertQuery);
0 Updation
String updateQuery;
updateQuery = "update StudentsInfo set Name=‘Ayele' where Id=1";
stmt.execute(updateQuery);
0 Deletion
String deleteQuery;
deleteQuery = "delete from StudentsInfo where Id=1";
stmt.execute(deleteQuery);
0 Selection
The return value is a ResultSet object containing rows of the database table
that are retrieved from the database.
ResultSet rs = stmt.executeQuery("seletct * from StudentInfo");
Adv. Prog : JDBC 37
38. Task Three:
Setting up the JDBC connection
Step 5: Closing Database Connection.
h rs.close();
stmt.close();
connection.close();
Adv. Prog : JDBC 38
39. Skeleton Code
Class.forName(DRIVERNAME);
Connection con ;
con = DriverManager.getConnection(CONNECTIONURL, DBID,DBPASS);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member);
While(rs.next())
{
Int x = rs.getInt(“a”);
String s = rs.getString(“b”);
Float f = rs.getFloat(“c”);
}
rs.close();
stmt.close();
con.close();
Adv. Prog : JDBC 39
Loading a JDBC driver
Connecting to a database
Processing the result set
Closing the connections
Executing SQL
40. Processing the Results (1/2)
0 JDBC returns the results of a query in a ResultSet object
0 ResultSet object contains all of the rows which satisfied the
conditions in an SQL statement
0 A ResultSet object maintains a cursor pointing to its current row of data
0 Use next() to step through the result set row by row
0next() returns TRUE if there are still remaining records
0 getString(), getInt(), and getXXX() assign each value to a Java
variable
Adv. Prog : JDBC
40
Record 1 Record 2 Record 3 Record 4
ResultSet
Internal Pointer
The internal pointer starts one before the first record
41. Processing the Results (2/2)
0 Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT * FROM StudentInfo”);
While (rs.next()){
int id = rs.getInt(“Id”);
String name = rs.getString(“Name”);
System.out.println(“ID= ” + id + “ t Name= ” + Name );
}
Adv. Prog : JDBC 41
NOTE
You must step the cursor to the first record before read the
results This code will not skip the first record
ID Name
1 Deribe
2 Adenagir
3 Tase
Table1
Output
ID=1 Name=Deribe
ID=2 Name=Adenagir
ID=3 Name=Tase
42. Sample Full Program
import java.sql.*;
public class StudentDerbyDemo {
public static void main(String[] args) {
try{// let's try to register the derby client driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
}catch(ClassNotFoundException e){
System.out.println("Driver Missing!");
}
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
//let's connect to the database via our registered driver
String url = "jdbc:derby://localhost:1527/StudentDB“;
con = DriverManager.getConnection (url, "student", "student");
//let's create a statement in order to query the tables
stmt = con.createStatement();
Adv. Prog : JDBC 42
43. Sample Full Program
//********INSERTION********//
//let's first insert two students' information
stmt.execute("INSERT INTO StudentInfo VALUES (1,'Atnafu')");
stmt.execute("INSERT INTO StudentInfo VALUES (4,'Gume')");
System.out.println("insertion successfull");
//********SEARCHING********//
rs = stmt.executeQuery("SELECT * FROM StudentInfo WHERE Id=2");
System.out.println("Searching successful");
rs.next();//will point to the first fetched row(s)
System.out.println("Id : " + rs.getInt("Id") + "t Name :" + rs.getString("Name"));
// rs.getInt(“Id”) : - Id is the name of the column in StudentInfo table.
//********UPDATION********//
stmt.executeUpdate("UPDATE StudentInfo SET Name = 'Biritu' WHERE Id = 1");
System.out.println("Updation successfull");
//********DELETION********//
stmt.executeUpdate("DELETE FROM StudentInfo WHERE Id=1");
System.out.println("Deletion successfull");
Adv. Prog : JDBC 43
44. Sample Full Program
}catch(SQLException e){
System.out.println(e.toString());
}
finally{
try{ //Closing the connection
rs.close();
stmt.close();
con.close();
}catch(SQLException e){
System.out.println(e.toString());
}
}
}
}
Adv. Prog : JDBC 44
45.
46. JDBC - Statements
0 Once a connection is obtained we can interact with the
database. The JDBC Statement, CallableStatement, and
PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands
and receive data from your database.
0 They also define methods that help bridge data type
differences between Java and SQL data types used in a
database.
0 Following table provides a summary of each interface's
purpose to understand how do you decide which interface to
use?
Adv. Prog : JDBC 46
47. JDBC - Statements
Interfaces Recommended Use
Statement
Use for general-purpose access to your
database. Useful when you are using static SQL
statements at runtime. The Statement interface
cannot accept parameters.
PreparedStatement
Use when you plan to use the SQL statements
many times. The PreparedStatement interface
accepts input parameters at runtime.
CallableStatement
Use when you want to access database stored
procedures. The CallableStatement interface
can also accept runtime input parameters.
Adv. Prog : JDBC 47
48. The Statement Objects:
Adv. Prog : JDBC 48
Creating Statement Object:
0 Before you can use a Statement object to execute a SQL statement,
you need to create one using the Connection object's
createStatement( ) method, as in the following example:
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
49. The Statement Objects:
Adv. Prog : JDBC 49
0 Once you've created a Statement object, you can then use it to
execute a SQL statement with one of its three execute methods.
1. 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
or when you need to use truly dynamic SQL.
2. int executeUpdate(String SQL) : Returns the numbers 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.
3. 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.
50. The Statement Objects:
Adv. Prog : JDBC 50
Closing Statement Obeject:
0 Just as you close a Connection object to save database resources, for
the same reason you should also close the Statement object.
0 A simple call to the close() method will do the job. If you close the
Connection object first it will close the Statement object as well.
However, you should always explicitly close the Statement object to
ensure proper cleanup.
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
stmt.close();
}
51. The Statement Objects:
Adv. Prog : JDBC 51
…..
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
//let's create a statement in order to query the tables
stmt = con.createStatement();
stmt.execute("INSERT INTO StudentInfo VALUES (1,'Atnafu')");
…
}
…..
52. The PreparedStatement Objects
Adv. Prog : JDBC 52
0 The PreparedStatement interface extends the Statement
interface which gives you added functionality with a couple of
advantages over a generic Statement object.
0 This statement gives you the flexibility of supplying arguments
dynamically.
Creating PreparedStatement Object:
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}catch (SQLException e) {
. . .
}finally { . . .}
53. The PreparedStatement Objects
Adv. Prog : JDBC 53
0 All parameters in JDBC are represented by the ? symbol, which is
known as the parameter marker. You must supply values for every
parameter before executing the SQL statement.
0 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. If you forget to supply the values, you will receive an
SQLException.
0 Each parameter marker is referred to by its ordinal position. The first
marker represents position 1, the next position 2, and so forth. This
method differs from that of Java array indices, which start at 0.
0 All of the Statement object's methods for interacting with the
database (a) execute(), (b) executeQuery(), and (c) executeUpdate()
also work with the PreparedStatement object. However, the methods
are modified to use SQL statements that can take input the
parameters.
54. The PreparedStatement Objects
Adv. Prog : JDBC 54
Closing PreparedStatement Obeject:
0 Just as you close a Statement object, for the same reason you should also
close the PreparedStatement object.
0 A simple call to the close() method will do the job. If you close the
Connection object first it will close the PreparedStatement object as well.
However, you should always explicitly close the PreparedStatement object to
ensure proper cleanup
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}catch (SQLException e) {
. . .
}finally {
pstmt.close();
}
55. The PreparedStatement Objects
Adv. Prog : JDBC 55
Eg 1:
Try{
int price = 560000, id =1281;
….
PreparedStatement pst= null;
pst = con.prepareStatement("UPDATE CARS SET PRICE = ? WHERE ID = ?");
pst.setInt(1, price);
pst.setInt(2, id);
pst.executeUpdate();
…
Eg 2
PreparedStatement updateemp;
updateemp = con.prepareStatement ("insert into emp values(?,?,?)");
updateemp.setInt(1,23);
updateemp.setString(2,"Roshan");
updateemp.setString(3, "CEO");
updateemp.executeUpdate();
56. The CallableStatement Objects:
Adv. Prog : JDBC 56
0 Just as a Connection object creates the Statement and PreparedStatement
objects, it also creates the CallableStatement object which would be used to
execute a call to a database stored procedure.
0 A stored procedure is nothing more than prepared SQL code that you save so
you can reuse the code over and over again. So if you think about a query
that you write over and over again, instead of having to write that query
each time you would save it as a stored procedure and then just call the
stored procedure to execute the SQL code that you saved as part of the
stored procedure.
0 In addition to running the same SQL code over and over again you also have
the ability to pass parameters to the stored procedure, so depending on
what the need is the stored procedure can act accordingly based on the
parameter values that were passed.
57. The CallableStatement Objects:
Adv. Prog : JDBC 57
0 Just as a Connection object creates the Statement and PreparedStatement
objects, it also creates the CallableStatement object which would be used to
execute a call to a database stored procedure.
Creating CallableStatement Object:
0 Three types of parameters exist: IN, OUT, and INOUT. The
preparedStatement object only uses the IN parameter. The
CallableStatement object can use all three.
0 Here are the definitions of each:
Parameter Description
IN
A parameter whose value is unknown when the SQL statement is created.
You bind values to IN parameters with the setXXX() methods.
OUT
A parameter whose value is supplied by the SQL statement it returns. 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.
58. The CallableStatement Objects:
Adv. Prog : JDBC 58
0 The following code snippet shows how to employ the
Connection.prepareCall() method to instantiate a CallableStatement
object based on the preceding stored procedure:
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally { . . .}
59. The CallableStatement Objects:
Adv. Prog : JDBC 59
0 The String variable SQL represents the stored procedure, with parameter
placeholders.
0 Using CallableStatement objects is much like using PreparedStatement
objects. You must bind values to all parameters before executing the
statement, or you will receive an SQLException.
0 If you have IN parameters, just follow the same rules and techniques that
apply to a PreparedStatement object; use the setXXX() method that
corresponds to the Java data type you are binding.
0 When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The
registerOutParameter() method binds the JDBC data type to the data type
the stored procedure is expected to return.
0 Once you call your stored procedure, you retrieve the value from the OUT
parameter with the appropriate getXXX() method. This method casts the
retrieved value of SQL type to a Java data type.
60. The CallableStatement Objects:
Adv. Prog : JDBC 60
Closing CallableStatement Obeject:
0 Just as you close other Statement object, for the same reason you should also
close the CallableStatement object.
0 A simple call to the close() method will do the job. If you close the Connection
object first it will close the CallableStatement object as well. However, you
should always explicitly close the CallableStatement object to ensure proper
cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
cstmt.close();
}
61. JDBC - Result Sets
Adv. Prog : JDBC 61
0 The SQL statements that read data from a database query return the data in
a result set. 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.
0 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.
0 The methods of the ResultSet interface can be broken down into three
categories:
1. Navigational methods: used to move the cursor around.
2. Get methods: used to view the data in the columns of the current row
being pointed to by the cursor.
3. Update methods: used to update the data in the columns of the current
row. The updates can then be updated in the underlying database as well.
62. JDBC - Result Sets
Adv. Prog : JDBC 62
0 The cursor is movable based on the properties of the ResultSet. These
properties are designated when the corresponding Statement that generated
the ResultSet is created.
0 JDBC provides following connection methods to create statements with
desired ResultSet:
1. createStatement(int RSType, int RSConcurrency);
2. prepareStatement(String SQL, int RSType, int RSConcurrency);
3. prepareCall(String sql, int RSType, int RSConcurrency);
0 The first argument indicate the type of a ResultSet object and the second
argument is one of two ResultSet constants for specifying whether a result
set is read-only or updatable.
63. JDBC - Result Sets
Adv. Prog : JDBC 63
Type of ResultSet:
0 The possible RSType are given below, If you do not specify any ResultSet
type, you will automatically get one that is TYPE_FORWARD_ONLY.
Type Description
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, and
the result set is not sensitive to changes made by
others to the database that occur after the result set
was created.
ResultSet.TYPE_SCROLL_SENSITIVE.
The cursor can scroll forwards and backwards, and
the result set is sensitive to changes made by others
to the database that occur after the result set was
created.
64. JDBC - Result Sets
Adv. Prog : JDBC 64
Concurrency of ResultSet:
0 The possible RSConcurrency are given below, If you do not specify any
Concurrency type, you will automatically get one that is
CONCUR_READ_ONLY.
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
65. JDBC - Result Sets
Adv. Prog : JDBC 65
0 Our all the examples written so far can be written as follows which
initializes a Statement object to create a forward-only, read only ResultSet
object:
try {
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally { ....}
66. JDBC - Result Sets
Adv. Prog : JDBC 66
Navigating a Result Set:
0 There are several methods in the ResultSet interface that involve moving the
cursor, including:
S.N. Methods & Description
1
public void beforeFirst() throws SQLException
Moves the cursor to just before the first row
2
public void afterLast() throws SQLException
Moves the cursor to just after the last row
3
public boolean first() throws SQLException
Moves the cursor to the first row
4
public void last() throws SQLException
Moves the cursor to the last row.
5
public boolean absolute(int row) throws SQLException
Moves the cursor to the specified row
67. JDBC - Result Sets
Adv. Prog : JDBC 67
Navigating a Result Set:
S.N. Methods & Description
6
public boolean relative(int row) throws SQLException
Moves the cursor the given number of rows forward or backwards from where it currently is
pointing.
7
public boolean previous() throws SQLException
Moves the cursor to the previous row. This method returns false if the previous row is off the
result set
8
public boolean next() throws SQLException
Moves the cursor to the next row. This method returns false if there are no more rows in the
result set
9
public int getRow() throws SQLException
Returns the row number that the cursor is pointing to.
10
public void moveToInsertRow() throws SQLException
Moves the cursor to a special row in the result set that can be used to insert a new row into the
database. The current cursor location is remembered.
11
public void moveToCurrentRow() throws SQLException
Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise,
this method does nothing
68. JDBC - Result Sets
Adv. Prog : JDBC 68
Viewing a Result Set:
0 The ResultSet interface contains dozens of methods for getting the data of
the current row.
0 There is a get method for each of the possible data types, and each get
method has two versions:
1. One that takes in a column name.
2. One that takes in a column index.
0 For example, if the column you are interested in viewing contains an int, you
need to use one of the getInt() methods of ResultSet:
S.N. Methods & Description
1
public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named columnName
2
public int getInt(int columnIndex) throws SQLException
Returns the int in the current row in the specified column index. The column index starts at
1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
69. JDBC - Result Sets
Adv. Prog : JDBC 69
0 Similarly there are get methods in the ResultSet interface for each of the
eight Java primitive types, as well as common types such as java.lang.String,
java.lang.Object, and java.net.URL
0 There are also methods for getting SQL data types java.sql.Date,
java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the
documentation for more information about using these SQL data types.
ResultSet Methods
• String getString(int columnIndex)
• boolean getBoolean(int columnIndex)
• byte getByte(int columnIndex)
• short getShort(int columnIndex)
• int getInt(int columnIndex)
• long getLong(int columnIndex)
• float getFloat(int columnIndex)
• double getDouble(int columnIndex)
• Date getDate(int columnIndex)
• Time getTime(int columnIndex)
• Timestamp getTimestamp(int columnIndex)
70. JDBC - Result Sets
Adv. Prog : JDBC 70
ResultSet Methods
0 isNull
0 In SQL, NULL means the field is empty
0 Not the same as 0 or “”
0 In JDBC, you must explicitly ask if a field is null by calling
ResultSet.isNull(column)
0 getMaxRows/setMaxRows
– Maximum number of rows a ResultSet may contain
– Unless explicitly set, the number of rows is unlimited (return value
of 0)
71. JDBC - Result Sets
Adv. Prog : JDBC 71
Updating a Result Set:
0 The ResultSet interface contains a collection of update methods for updating
the data of a result set.
0 As with the get methods, there are two update methods for each data type:
1. One that takes in a column name.
2. One that takes in a column index.
0 For example, to update a String column of the current row of a result set, you
would use one of the following updateString() methods:
S.N. Methods & Description
1
public void updateString(int columnIndex, String s) throws SQLException
Changes the String in the specified column to the value of s.
2
public void updateString(String columnName, String s) throws SQLException
Similar to the previous method, except that the column is specified by its name
instead of its index.
72. JDBC - Result Sets
Adv. Prog : JDBC 72
Updating a Result Set:
0 There are update methods for the eight primitive data types, as well as String, Object,
URL, and the SQL data types in the java.sql package.
0 Updating a row in the result set changes the columns of the current row in the
ResultSet object, but not in the underlying database. To update your changes to the
row in the database, you need to invoke one of the following methods.
S.N. Methods & Description
1
public void updateRow()
Updates the current row by updating the corresponding row in the database.
2
public void deleteRow()
Deletes the current row from the database
3
public void refreshRow()
Refreshes the data in the result set to reflect any recent changes in the database.
4
public void cancelRowUpdates()
Cancels any updates made on the current row.
5
public void insertRow()
Inserts a row into the database. This method can only be invoked when the cursor is
pointing to the insert row.
73. Date & Time Data Types:
73
0 The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and
java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data
types, respectively.
0 JDBC in Java has three date/time types corresponding to DATE, TIME and TIMESTAMP
type of ANSI SQL. These types are used to convert SQL types into Java types.
1. First difference on java.sql.Time vs java.sql.Timestamp vs java.sql.Date is about
information they represent :
JDBC TIME or java.sql.Time represent only time information e.g. hours, minutes and
seconds without any date information.
JDBC DATE or java.sql.Date represent only date information e.g. year, month and day
without any time information.
JDBC TIMESTAMP or java.sql.Timestamp represent both date and time information
including nanosecond details.
2. java.sql.Time and java.sql.Timestamp extends java.util.Date class but java.sql.Date is
independent.
3 Time information from java.sql.Date and Date information from java.sql.Time is
normalized and may set to zero in order to confirm ANSI SQL DATE and TIME types.
0 So difference between Time, Timestamp and Date of SQL package is clear in terms of what
they represent. On contrary java.util.Date also represent Date and time information but
without nanosecond details and that's why many people prefer to store date as long
value (millisecond passed from epoch January 1, 1970 00:00:00.000 GMT). If you compare
to java.sql.Timestamp with equals() method it will return false as value of nanosecond is
unknown.
74. Handling NULL Values
Adv. Prog : JDBC 74
0 SQL's use of NULL values and Java's use of null are different concepts. So how do
you handle SQL NULL values in Java? There are three tactics you can use:
0 Avoid using getXXX( ) methods that return primitive data types.
0 Use wrapper classes for primitive data types, and use the ResultSet object's
wasNull( ) method to test whether the wrapper class variable that received the
value returned by the getXXX( ) method should be set to null.
0 Use primitive data types and the ResultSet object's wasNull( ) method to test
whether the primitive variable that received the value returned by the getXXX( )
method should be set to an acceptable value that you've chosen to represent a
NULL.
0 Here is one example to handle a NULL value:
Statement stmt = conn.createStatement( );
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
int id = rs.getInt(1);
if( rs.wasNull( ) ) {
id = 0;
}
75. JDBC - Transactions
Adv. Prog : JDBC 75
0 If your JDBC Connection is in auto-commit mode, which it is by default, then
every SQL statement is committed to the database upon its completion.
0 That may be fine for simple applications, but there are three reasons why
you may want to turn off auto-commit and manage your own transactions:
To increase performance
To maintain the integrity of business processes
To use distributed transactions
0 Transactions enable you to control if, and when, changes are applied to the
database. It treats a single SQL statement or a group of SQL statements as
one logical unit, and if any statement fails, the whole transaction fails.
0 To enable manual- transaction support instead of the auto-commit mode
that the JDBC driver uses by default, use the Connection object's
setAutoCommit() method. If you pass a boolean false to setAutoCommit( ),
you turn off auto-commit. You can pass a boolean true to turn it back on
again.
0 For example, if you have a Connection object named conn, code the following
to turn off auto-commit:
conn.setAutoCommit(false);
76. JDBC - Transactions
• By default, after each SQL statement is executed the changes
are automatically committed to the database
– Turn auto-commit off to group two or more statements together
into a transaction:
connection.setAutoCommit(false);
– Call commit to permanently record the changes to the database
after executing a group of statements
– Call rollback if an error occurs
0 Transaction: more than one statement that must all succeed
(or all fail) together
Ex) updating several tables due to customer purchase
0 If one fails, the system must reverse all previous actions
0 Also can’t leave DB in inconsistent state halfway through a
transaction
0 COMMIT = complete transaction
0 ROLLBACK = cancel all actions
76
Adv. Prog : JDBC
77. JDBC - Transactions
0 The connection has a state called AutoCommit mode
0 If AutoCommit is true, then every statement is automatically
committed
0 If AutoCommit is false, then every statement is added to an ongoing
transaction
0 Default: true
Adv. Prog : JDBC 77
con.setAutoCommit(false);
try {
PreparedStatement pstmt = con.prepareStatement(
"update BankAccount set amount = amount + ? where accountId = ?");
pstmt.setInt(1,-100); pstmt.setInt(2, 13);
pstmt.executeUpdate();
pstmt.setInt(1, 100); pstmt.setInt(2, 72);
pstmt.executeUpdate();
con.commit();
catch (SQLException e)
{ con.rollback(); }
78. Useful Transaction Methods
• These methods apply to the Connection
• getAutoCommit/setAutoCommit
– By default, a connection is set to auto-commit
– Retrieves or sets the auto-commit mode
• Commit
– All changes since last commit to become permanent
– Database locks held by this Connection are released
• rollback
– Drops all changes since the previous call to commit
– Releases database locks held by this Connection object
78
Adv. Prog : JDBC
80. Commit & Rollback
Adv. Prog : JDBC 80
0 Once you are done with your changes and you want to commit the changes
then call commit() method on connection object as follows:
conn.commit( );
0 Otherwise, to roll back updates to the database made using the Connection
named conn, use the following code:
conn.rollback( );
0 The following example illustrates the use of a commit and rollback object:
81. Commit & Rollback
Adv. Prog : JDBC 81
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In this case none of the above INSERT statement would success and everything
would be rolled back.
82. Using Savepoints
Adv. Prog : JDBC 82
0 The new JDBC 3.0 Savepoint interface gives you additional transactional
control. Most modern DBMS support savepoints within their environments
such as Oracle's PL/SQL.
0 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.
0 The Connection object has two new methods that help you manage
savepoints:
1. setSavepoint(String savepointName): defines a new savepoint. It also
returns a Savepoint object.
2. releaseSavepoint(Savepoint savepointName): deletes a savepoint.
Notice that it requires a Savepoint object as a parameter. This object is
usually a savepoint generated by the setSavepoint() method.
0 There is one rollback ( String savepointName ) method which rolls back
work to the specified savepoint.
0 The following example illustrates the use of a Savepoint object:
83. Using Savepoints
Adv. Prog : JDBC 83
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback(savepoint1);
}
In this case none of the abobe INSERT statement would success and everything would be rolled back.
85. Using JDBC MetaData
• Metadata: “data about the data”
– Not “How many customers have sales over $100K?” but
“How many columns have a datatype of BIT (boolean)?”
• System-wide data
– connection.getMetaData().getDatabaseProductName()
– connection.getMetaData().getDatabaseProductVersion()
• Table-specific data
– resultSet.getMetaData().getColumnCount()
• When using the result, remember that the index starts at 1,
not 0
– resultSet.getMetaData().getColumnName()
85
Adv. Prog : JDBC
86. ResultSetMetaData answers:
• What's the number of columns in the ResultSet?
• What's a column's name?
• What's a column's SQL type?
• What's the column's normal max width in chars?
• What's the suggested column title for use in printouts and displays?
• What's a column's number of decimal digits?
• Does a column's case matter?
• Is the column a cash value?
• Will a write on the column definitely succeed?
• Can you put a NULL in this column?
• Is a column definitely not writable?
• Can the column be used in a where clause?
• Is the column a signed number?
• Is it possible for a write on the column to succeed?
• and so on...
86
Adv. Prog : JDBC
87. DatabaseMetaData answers:
0 What tables are available?
0 What's our user name as known to the database?
0 Is the database in read-only mode?
0 If table correlation names are supported, are they
restricted to be different from the names of the
tables?
0 and so on…
87
Adv. Prog : JDBC
88. Summary
0 JDBC
0 Standard interface for connecting to relational
databases from Java
0 Vendor independent API for accessing relational data
0 JDBC has four driver type
0JDBC-ODBC bridge plus ODBC driver
0Native-API partly-Java driver
0JDBC-Net pure Java driver
0Native Protocol pure Java API driver
0 JDBC support transaction and PreparedStatement
Adv. Prog : JDBC 88
89. Online Resources
0 Tutorialspoint.com
http://www.tutorialspoint.com/javaexamples/java_jdbc.htm
0 Sun’s JDBC site
0 http://java.sun.com/products/jdbc/
0 JDBC tutorial
0 http://java.sun.com/docs/books/tutorial/jdbc/
0 List of available JDBC drivers
0 http://developers.sun.com/product/jdbc/drivers
0 API for java.sql
0 http://java.sun.com/j2se/1.5.0/docs/api/java/sql/package-summary.html
Adv. Prog : JDBC 89