Chapter 4 - JDBC (FULL)
Chapter 4 - JDBC (FULL)
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
Database
JAVA Applet/ JDBC Call Command
Application JDBC Driver Database
Oracle
Driver
Oracle
Java DB2
Application JDBC
Driver
DB2
Network
MySQL
Driver
java.sql.package
java.sql.DriverManager
(JDBC library)
4. Connection
supplied by
Driver for MySQL Driver for Oracle DriverManager is
databases databases used by
application to talk
How JDBC establishes a JDBC through
connection between your the driver to the
MySQL
code and a database database.
DB
JDBC Programming Steps
1) Register the driver
Connect 2) Create a connection to the database
1) Create a statement
Query 2) Query the database
Click on Windows->
Services.
h rs.close();
stmt.close();
connection.close();
Class.forName(DRIVERNAME);
Connecting to a database
Connection con ;
con = DriverManager.getConnection(CONNECTIONURL, DBID,DBPASS);
rs.close();
stmt.close(); Closing the connections
con.close();
Adv. Prog : JDBC 39
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
0 next() returns TRUE if there are still remaining records
0 getString(), getInt(), and getXXX() assign each value to a Java
variable
Output
ID Name
1 Deribe
ID=1 Name=Deribe
2 Adenagir
ID=2 Name=Adenagir
3 Tase ID=3 Name=Tase
Table1 Adv. Prog : JDBC 41
Sample Full Program
import java.sql.*;
public class StudentDerbyDemo {
A parameter that provides both input and output values. You bind
INOUT variables with the setXXX() methods and retrieve values with the
Adv. Prog : JDBC 57
getXXX() methods.
The CallableStatement Objects:
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 { . . .}
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
Concurrency Description
0 getMaxRows/setMaxRows
– Maximum number of rows a ResultSet may contain
– Unless explicitly set, the number of rows is unlimited (return value
of 0)
int id = rs.getInt(1);
if( rs.wasNull( ) ) {
id = 0;
} Adv. Prog : JDBC 74
JDBC - Transactions
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);
Adv. Prog : JDBC 75
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
Adv. Prog : JDBC 76
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
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(); }
Adv. Prog : JDBC 77
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
//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.
Adv. Prog : JDBC 83
JDBC Class Diagram
Whoa! 84
Adv. Prog : JDBC
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()