03 Java JDBC
03 Java JDBC
Demchyna Mykola
October, 2014
Agenda
1. What is JDBC?
2. Introduction to JDBC
3. JDBC Architecture
4. Basic steps to use a database in Java
5. About Prepared Statements
6. Result Set
7. Mapping Java Types to SQL Types
8. Transactions and JDBC
9. Scrollable Result Set
10. Conclusion
11. References
1. What is JDBC
▪ What’s a JDBC?
– “An API that lets you access practically any
tabular data source from the Java
programming language”.
▪ What’s a tabular data source?
– “… access practically many data source, from
relational databases to spreadsheets and flat
files.”
2. Introduction to JDBC
Oracle
We will Driver
use this one…
Oracle
Java MySQL
Application JDBC
Driver
MySQL
Network
DB2
Driver
DB2
JDBC Architecture (cont.)
▪ 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.
▪ Ideal: can change database engines without
changing any application code.
DB
ResultSet rs = stmt.executeQuery(queryStr);
String queryStr =
"SELECT * FROM employee " +
"WHERE name = ? AND salary > ?";
PreparedStatement pstmt =
con.prepareStatement(queryStr);
pstmt.setString(1, "Ivan");
pstmt.setInt(2, 5200);
ResultSet rs = pstmt.executeQuery();
Updating with PreparedStatement
String deleteStr =
"DELETE FROM employee " +
"WHERE name = ? AND salary > ?";
PreparedStatement pstmt =
con.prepareStatement(deleteStr);
pstmt.setString(1, "Artur");
pstmt.setDouble(2, 4600);
PreparedStatement pstmt =
con.prepareStatement("SELECT * FROM ?");
pstmt.setString(1, myFavoriteTableString);
▪ boolean next()
– activates the next row;
– the first call to next() activates the first row;
– returns false if there are no more rows.
▪ void close()
– allows you to re-use the Statement that
created it;
– automatically called by most Statement
methods.
Result Set Methods (cont.)
▪ Type getType(int columnIndex)
– returns the given field as the given type
– indices start at 1 but not 0!
▪ Type getType(String columnName)
– same, but uses name of field
– less efficient
▪ int findColumn(String columnName)
– looks up column index given column name
Example (Result Set)
con.close();
stmt.close();
pstmt.close();
rs.close()
8. Transactions and JDBC
▪ Transaction: more than one statement that
must all succeed (or all fail) together
– e.g., updating several tables due to customer
purchase
▪ If one fails, the system must reverse all previous
actions
▪ Also can’t leave DB in inconsistent state
halfway through a transaction
– COMMIT = complete transaction
– ROLLBACK = cancel all actions
Transaction Management
▪ The connection has a state called
AutoCommit mode
▪ if AutoCommit is true, then every statement
is automatically committed
▪ if AutoCommit is false, then every
statement is added to an ongoing
transaction
▪ Default: true
AutoCommit
setAutoCommit(boolean val)
▪ If you set AutoCommit to false, you must
explicitly commit or rollback the transaction
using
– Connection.commit()
and
– Connection.rollback()
Example (Transactions)
▪ Suppose we want to transfer money from bank account 1 to account 2:
try {
con.setAutoCommit(false);
PreparedStatement pstmt =
con.prepareStatement("UPDATE BankAccount SET
amount = amount + ? WHERE accountId = ?");
pstmt.setInt(1, 300);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
pstmt.setInt(1, 700); What happens if this
pstmt.setInt(2, 2); update fails?
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
}
9. Scrollable Result Set
▪ Statement createStatement(int resultSetType,
int resultSetConcurrency)
resultSetType:
▪ ResultSet.TYPE_FORWARD_ONLY
– default; same as in JDBC 1.0
– allows only forward movement of the cursor
– when rs.next() returns false, the data is no longer available
and the result set is closed.
▪ ResultSet.TYPE_SCROLL_INSENSITIVE
– backwards, forwards, random cursor movement.
– changes made in the database are not seen in the result set
object in Java memory.
Scrollable Result Set (const.)
▪ ResultSet.TYPE_SCROLL_SENSITIVE
– backwards, forwards, random cursor movement.
– changes made in the database are seen in the result
set object in Java memory.
▪ ResultSet.CONCUR_READ_ONLY
– This is the default (and same as in JDBC 1.0) and
allows only data to be read from the database.
▪ ResultSet.CONCUR_UPDATABLE
– This option allows for the Java program to make
changes to the database based on new methods
and positioning ability of the cursor.
9. Scrollable Result Set
▪ public boolean absolute(int row) throws
SQLException
– If the given row number is positive, this method moves the
cursor to the given row number (with the first row numbered 1).
– If the given row number is negative, the cursor moves to an
absolute row position with respect to the end of the result set.
For example, calling the method absolute(-1) positions the
cursor on the last row; calling the method absolute(-2) moves
the cursor to the next-to-last row, and so on.
– If the row number specified is zero, the cursor is moved to before
the first row.
– An attempt to position the cursor beyond the first/last row in the
result set leaves the cursor before the first row or after the last
row.
9. Scrollable Result Set
▪ public boolean relative(int row) throws
SQLException
– Moves the cursor a relative number of rows, either
positive or negative.
– Attempting to move beyond the first/last row in the
result set positions the cursor before/after the first/last
row.
– Calling relative(0) is valid, but does not change the
cursor position.
– Calling the method relative(1) is identical to calling the
method next() and calling the method relative(-1) is
identical to calling the method previous().
Scrollable Result Set (const.)
▪ public int getRow() throws SQLException
– getRow() method retrieves the current row number (the first
row is number 1, the second number 2, and so on).
▪ public boolean first() throws SQLException
▪ public boolean last() throws SQLException
▪ public boolean previous() throws
SQLException
▪ public boolean next() throws SQLException
Exsample (Scrollable Result Set)
. . .
Statement stmt =
con.createStatement();
ResultSet rs = stmt.executeQuery(query);