DAT602 Database Application Development Lecture 9 Advanced JDBC 2.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

Database programming in Java An introduction to Java Database Connectivity (JDBC)
Object-Oriented Enterprise Application Development Advanced JDBC.
Java Database Connectivity JDBC ICW Lecture 12 Errol Thompson.
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
1 JDBC – Java Database Connectivity Modified slides from Dr. Yehoshua Sagiv.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
Databases: Queries with Java Dr Andy Evans. JDBC SQL Three methods: Statements: Standard, simple, SQL. PreparedStatements: Compiled SQL statements that.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Advanced SQL: Cursors & Stored Procedures
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 33 Advanced Java.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
JDBC Session 2 Tonight’s topics: 1.Prepared Statements 2.Transaction Processing 3.Callable Statements & Stored Procedures 4.Scrollable & Updatable Result.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
DAT602 Database Application Development Lecture 8 Advanced JDBC.
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
JDBC - Resultset The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
JDBC.
JDBC Java Data Base Connectivity נערך ע"י: אורי רוטנברג הנחיה: ד"ר תמר בניה קורס: סדנא ב-Java.
JDBC IV IS Outline  Batch processing  Transactions  Homework #2  Examples.
JDBC III IS Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures.
Chapter 38 Advanced Java Database Programming
JDBC III IS
Chapter 41 Advanced Java Database Programming
Error Handling Summary of the next few pages: Error Handling Cursors.
Objectives In this lesson, you will learn about:
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
JDBC – Java Database Connectivity
JDBC Example.
Presentation transcript:

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

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

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

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

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

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

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

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

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) …..

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

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) …..

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

Batch processing by using prepared statement The 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

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

Scrollable Result Sets What 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

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

Navigation of Scrollable Result Set While 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

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

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

Determining Where You Are You 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

Updatable Result Sets So 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

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

How to create a updatable result set ? Statement: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSIT IVE, 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

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

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 idbalance ……

Insert new row into updatable result set example: rs.moveToInsertRow( ); rs.updateString(1, "newuid"); rs.updateString(2, "newpass"); rs.insertRow( ); rs.moveToCurrentRow( ); Delete row You just have to call deleteRow( ). This method will delete the current row. Database Application Development - Lecture 9

Reference: Database Programming with JDBC and Java, Second Edition, George Reese O'Reilly & Associates, 2000 Chapter 3,4 Database Application Development - Lecture 9