dat602 database application development lecture 9 advanced jdbc 2

28
DAT602 Database Application Development Lecture 9 Advanced JDBC 2

Upload: elwin-mccarthy

Post on 04-Jan-2016

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

DAT602 Database Application Development

Lecture 9 Advanced JDBC 2

Page 2: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• In this lecture, we continue to introduce some advanced features of JDBC- Batch Processing- Scrollable Result Sets- Updatable Result Sets

Database Application Development - Lecture 9

Page 3: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• What is Batch Processing ?Batch processing is execution of a series of operations on a program without human interaction.

• Why we need batch processing ?Bank application automatically add interest to each account.

Database Application Development - Lecture 9

Page 4: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• JDBC 2.0 introduced new functionality to address the specific issues of batch processing. Using the JDBC 2.0 batch facilities, you can assign a series of SQL statements to a JDBC Statement (or one of its subclasses) to be submitted together for execution by the database.

Database Application Development - Lecture 9

Page 5: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• The advantage of applying batch processing. Here we use the bank application for illustration.

• The bank application adds interest to each account monthly. Without using batch processing, the steps should like:1. Prepare statement.2. Bind parameters.3. Execute.4. Repeat steps 2 and 3 for each account.

Database Application Development - Lecture 9

Page 6: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• In previous lecture, the example that not apply batch processing requires a lot of "back and forth" between the Java application and the database.

• These “back and forth” cost a lot of time.• JDBC 2.0 batch processing provides a simpler,

more efficient approach to this kind of processing, you can find in next slide.

Database Application Development - Lecture 9

Page 7: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• JDBC 2.0 provides batch processing:1. Prepare statement.2. Bind parameters.3. Add to batch.4. Repeat steps 2 and 3 until interest has been assigned for each account.5. Execute.Here, you can see that only one execute in whole operation, which means there is only one communication between application and database.

Database Application Development - Lecture 9

Page 8: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Under batch processing, there is no "back and forth" between the database for each account. Instead, all Java-level processing—the binding of parameters—occurs before you send the statements to the database.

Database Application Development - Lecture 9

Page 9: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Example: how to use a Statement object to batch process interest calculation:Statement stmt = conn.createStatement( );int[] rows;for(int i=0; i<accts.length; i++) {

accts[i].calculateInterest( );stmt.addBatch("UPDATE account " +"SET balance = " + accts[i].getBalance( ) +"WHERE acct_id = " + accts[i].getID( ));

}rows = stmt.executeBatch( );

Database Application Development - Lecture 9

Page 10: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Problems happen when the batch processing crash before it executes all statements.

Database Application Development - Lecture 9

Statement 1 (done)

Statement 2 (done)

Statement 3 (error)

Statement 4 (unfinished)

Statement 5 (unfinished)

Statement 6 (unfinished)

…..

Page 11: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

What will happen when error comes ?• All accounts before the error will have their

new balance stored in the database.• The subsequent accounts will not have had

their interest calculated.• The account where the error occurred will

have an account object whose state is inconsistent with the database.

Database Application Development - Lecture 9

Page 12: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• How should we to handle this issue ?

The key is know where the error happened, and we continue batch processing from the fail point.

Database Application Development - Lecture 9

Statement 1 (done)

Statement 2 (done)

Statement 3 (error)

Statement 4 (unfinished)

Statement 5 (unfinished)

Statement 6 (unfinished)

…..

Page 13: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• You can use the getUpdateCounts( ) method in the BatchUpdateException thrown by executeBatch() to get the value executeBatch() should have otherwise returned.

• Then you can continue your batch processing from the position getUpdateCounts() + 1.

Database Application Development - Lecture 9

Page 14: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Batch processing by using prepared statementThe main difference is that a batch prepared or callable statement represents a single SQL statement with a list of parameter groups, and the database should create a query plan only once.

Database Application Development - Lecture 9

Page 15: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Calculating interest with a prepared statement would look like this:PreparedStatement stmt = conn.prepareStatement("UPDATE account SET balance = ? WHERE acct_id = ?");int[] rows;for(int i=0; i<accts.length; i++) {

accts[i].calculateInterest( );stmt.setDouble(1, accts[i].getBalance( ));stmt.setLong(2, accts[i].getID( ));stmt.addBatch( );

}rows = stmt.executeBatch( );

Database Application Development - Lecture 9

Page 16: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Scrollable Result SetsWhat features scrollable can provide to us ?So far, if we want to loop all records of a result set, we only can loop forward. By using the scrollable result sets, we can loop both forward or backward, we can even jump to a specific position of result set.

Database Application Development - Lecture 9

Page 17: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• How to create a scrollable result set ?Statement stmt = Conn.createStatement(TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

First parameter of this constructor is used for indicating the scroll type, it also can be value TYPE_FORWARD_ONLY.

Database Application Development - Lecture 9

Page 18: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Navigation of Scrollable Result SetWhile next() moves one row forward, previous() moves one row backward. If it moves back beyond the first row, it returns false. Otherwise, it returns true.If you want loop whole set backward, you should call the method afterLast() first, this method move your to the row after last record of this set.

Database Application Development - Lecture 9

Page 19: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Skeleton of using previous method to loop whole set.stmt =con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);rs = stmt.executeQuery("SELECT * from test ORDER BY test_id");rs.afterLast( );while(rs.previous( )) {

String str;a = rs.getInt("test_id");

}

Database Application Development - Lecture 9

Page 20: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Move to specific position.You can call method absolute(int rowNumber) to move to specific position.Example of absolute()

resultSet.absolute(2)

What is more? beforeFirst(), last(), first()

Database Application Development - Lecture 9

Page 21: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Determining Where You AreYou can use following method to determe where you are, there methods return value true or false except method getRow(), getRow returns current row number as an integer.isFirst(), isLast(), isBeforeFirst(), isAfterLast(), and getRow( ).

Database Application Development - Lecture 9

Page 22: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Updatable Result SetsSo far, as we know, result is not updatable, which means you can’t modify the content of ResultSet, the content is read only.When our update is based on the stored content, we need two transaction to achieve our goal: select and update.

Database Application Development - Lecture 9

Page 23: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Why we need updatable result set ?An updatable result set enables you to perform in-place changes to a result set and have them take effect using the current transaction.

Database Application Development - Lecture 9

Page 24: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• How to create a updatable result set ?Statement:Statement stmt =con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);Prepared Statement PreparedStatement stmt = conn.prepareStatement("SELECT acct_id, balance FROM account“, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

Database Application Development - Lecture 9

Page 25: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Your updatable set must include primary key.The most important thing to remember about updatable result sets is that you must always select from a single table and include the primary key columns. If you don't, the concept of the result set being updatable is nonsensical.

Database Application Development - Lecture 9

Page 26: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• How to perform update in updatable result set ?while( rs.next( ) ) {

long acct_id = rs.getLong(1);double balance = rs.getDouble(2);balance = balance + (balance * 0.03)/12;rs.updateDouble(2, balance);rs.updateRow( );

}

Database Application Development - Lecture 9

id balance

101 35940.30

102 584920.49

103 3847.20

… …

Page 27: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Insert new row into updatable result setexample:

rs.moveToInsertRow( );rs.updateString(1, "newuid");rs.updateString(2, "newpass");rs.insertRow( );rs.moveToCurrentRow( );

• Delete rowYou just have to call deleteRow( ). This method will delete the current row.

Database Application Development - Lecture 9

Page 28: DAT602 Database Application Development Lecture 9 Advanced JDBC 2

• Reference:Database Programming with JDBC and Java, Second Edition, George ReeseO'Reilly & Associates, 2000Chapter 3,4

Database Application Development - Lecture 9