JDBC 4.0 and Oracle JDeveloper for J2EE Development - Deepak Vohra - E-Book

JDBC 4.0 and Oracle JDeveloper for J2EE Development E-Book

Vohra Deepak

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

In Detail



Data retrieval and storage is one of the most common components of J2EE applications. JDBC (Java Database Connectivity) is the Java API for accessing a SQL relational database and adding, retrieving, and updating data in the database.



Oracle JDeveloper is a developer-friendly integrated development environment (IDE) for building service-oriented applications using the latest industry standards for Java, XML, web services, and SQL. It supports the complete development lifecycle with integrated features for modeling, coding, debugging, testing, profiling, tuning, and deploying applications.



This book is about developing Java/J2EE applications with a database component in Oracle JDeveloper (version 10.1.3). It covers the practical aspects of JDBC (version 4.0); it will teach application developers about setting the environment for developing various JDBC-based J2EE applications and the procedure to develop JDBC-based J2EE applications. It will also explore the new features added in JDBC 4.0.



This book is a practical reference guide to using Oracle JDeveloper IDE and JDBC 4.0 to develop J2EE data-driven applications.

Approach



Being a quick reference guide, this book has a focused approach. You will learn to develop J2EE applications with JDBC and JDeveloper in no time. The book covers lot of practical examples, which makes it developer-friendly learning material.

Who this book is for



The book is suitable for Java/J2EE and Oracle JDeveloper beginners. If you are a J2EE developer and want to use the JDeveloper IDE for J2EE development, this book is for you. JDeveloper developers who are new to J2EE will also benefit from the book. Most J2EE applications have a database component and the book is specially suited for database-based J2EE development in Oracle JDeveloper. You can also use this book if you are interested in learning how to utilize the new features offered in JDBC 4.0 for Java/J2EE development. 

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 348

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

JDBC 4.0 and Oracle JDeveloper for J2EE Development
Credits
About the Author
About the Reviewer
Preface
What This Book Covers
Who is This Book for
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errata
Questions
1. JDBC 4.0
DriverManager Class
Connection Interface
Transactions
Savepoint Interface
Statement Interface
ResultSet Interface
PreparedStatement Interface
Database Metadata
JDBC Exceptions
New Features in JDBC 4.0
Automatic SQL Driver Loading
Enhanced Data Type Support
SQL: 2003 XML Data Type Support
Generating an XML Document
Storing an XML Document
Retrieving an XML Document
Accessing an XML Document Data
Support for Wrapper Pattern
Enhancements in SQLException
Connection Management
Scalar Functions
JDBC 4.0 support in Oracle Database
JDBC 4.0 support in MySQL Database
JDBC 4.0 support in IBM's DB2 UDB
Example Connection using a JDBC 4.0 Driver
Summary
2. Configuring JDBC in Oracle JDeveloper
Connection Pooling and DataSource
Setting the Environment
JDBC Configuration Errors
Creating a Managed Data Source
Connecting to a Database from a Web Application
Setting J2SE Version to JDK 6.0
Developing and Running JSP
JDBC 4.0 Version
Summary
3. Connecting to a Database with JSTL SQL Tag Library
Overview of JSTL SQL and Core Tags
Setting the Environment
Creating a Database Table
Updating a Database Table
Querying a Database Table
Summary
4. Configuring JDBC in JBoss Application Server
Deploying a Web Application to JBoss from JDeveloper
JDBC 4.0 Version
JBoss Deployment Descriptors for EJBs
Configuring JBoss Server with Oracle Database
Configuring JBoss Server with MySQL Database
Configuring JBoss Server with PostgreSQL Database
Configuring JBoss Server with DB2 Database
Configuring JBoss Server with SQL Server
Summary
5. Configuring JDBC in WebLogic Server
Setting the Environment
Creating a Data Source
Configuring a Data Source
Creating a Multi Data Source
Performance Tuning JDBC
Deploying a Web Application to WebLogic Server from JDeveloper
JDBC 4.0 Version
Summary
6. Configuring JDBC in WebSphere Application Server
Setting the Environment
Configuring a JDBC Provider
Configuring a Data Source
Deploying a Web Application to the WebSphere from JDeveloper
JDBC 4.0 Version
Summary
7. XML SQL Utility
Setting the Environment
XML Document to SQL Database Mapping
Updating Database from XML Document
Deleting a Row in a Database
SQL Database to XML Document Mapping
Summary
8. XSQL
Overview of XSQL Tags
Setting the Environment
Configuring a Connection
Creating XSQL Queries
Applying XSQL Query Attributes
Transforming XSQL Output
JDBC 4.0 Version
Summary
9. Oracle Web RowSet
Setting the Environment
Creating a Web RowSet
Modifying a Database Table with Web RowSet
Creating a New Row
Reading a Row
Updating a Row
Deleting a Row
Updating Database Table
JDBC 4.0 Version
Summary
10. Creating a JSF Data Table
Setting the Environment
Creating a Data Table by Binding a MBean
Creating a Data Table with the JSF API
JDBC 4.0 Version
Summary
11. Creating a JSF Panel Grid
Setting the Environment
Creating a Panel Grid by Binding Rows
Creating a Panel Grid by Binding a Managed Bean
JDBC 4.0 Version
Summary
12. Creating a Report with JasperReports
Setting the Environment
Installing JasperReports
Configuring the JasperReports Configuration File
Generating a PDF Report
Creating an Excel Spreadsheet
JDBC 4.0 Version
Summary
13. Creating a Spreadsheet with Apache POI
Setting the Environment
Creating an Excel Spreadsheet
JDBC 4.0 Version
Summary
14. Creating Oracle ADF Business Components
Setting the Environment
Configuring a BC4J Project
Creating Business Components
Developing a BC4J Web Application
JDBC 4.0 Version
Summary
15. Hibernate
Hibernate and JDBC
Setting the Environment
Developing Hibernate Mapping and Properties Files
Creating a Database Table
Modifying Table Data with Hibernate
Adding Data to the Database Table
Retrieving Data from the Database Table
Updating the Database Table
Deleting Data
Summary
Index

JDBC 4.0 and Oracle JDeveloper for J2EE Development

Deepak Vohra

JDBC 4.0 and Oracle JDeveloper for J2EE Development

Copyright © 2008 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: April 2008

Production Reference: 1230408

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847194-30-5

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Author

Deepak Vohra

Reviewer

Frank Nimphius

Acquisition Editor

Shayantani Chaudhuri

Development Editor

Ved Prakash Jha

Technical Editors

Akshara Aware

Rashmi Balachandran

Code Testing

Rashmi Balachandran

Copy Editing

Sumathi Sridhar

Editorial Team Leader

Mithil Kulkarni

Project Manager

Abhijeet Deobhakta

Project Coordinator

Lata Basantani

Indexer

Monica Ajmera

Proofreaders

Chris Smith

Camille Guy

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Deepak Vohra is a consultant and a principal member of the NuBean software company. Deepak is a Sun Certified Java Programmer and Web Component Developer, and has worked in the fields of XML and Java programming and J2EE for over five years. Deepak is the co-author of the APress book, Pro XML Development with Java Technology and was the technical reviewer for the OReilly book, WebLogic: The Definitive Guide. Deepak was also the technical reviewer for the Course PTR book, Ruby Programming for the Absolute Beginner, and the technical editor for the Manning Publications book, Prototype and Scriptaculous in Action.

About the Reviewer

Frank Nimphius is a Principal Product Manager for application development tools at Oracle Corporation since 1999. Working from Germany, Frank actively contributes to the development of Oracle JDeveloper and the Oracle Application Development Framework (ADF). As a conference speaker, Frank represents the Oracle J2EE development team at J2EE conferences world wide, including various Oracle user groups and the Oracle Open World conference

Preface

Data retrieval and storage are one of the most common components of J2EE applications. JDBC (Java DataBase Connectivity) is the Java API for accessing a Structured Query Language (SQL) relational database and adding, retrieving, and updating data in the database. JDBC 3.0 specification is the current specification implemented by most application servers. JDBC 4.0 specification became available in December 2006, but is not yet implemented by most application servers such as Oracle Application Server, WebLogic Server, JBoss Application Server, and WebSphere Application Server.

To connect with a SQL relational database, a JDBC driver is required; and most databases provide a JDBC 4.0 driver. We will use the Oracle JDeveloper 10.1.3 IDE to develop most of the J2EE applications in the book. We have chosen JDeveloper, because it includes an embedded J2EE server, the Oracle Containers for J2EE (OC4J) server, to run J2EE applications. JDeveloper also provides built-in support to connect to any of the commonly used application servers such as Oracle Application Server, WebLogic Server, JBoss Application Server, Tomcat server, and WebSphere Application Server and deploy applications to these servers. Another advantage of using JDeveloper is that JDeveloper provides built-in support for JDBC. JDeveloper also provides support for JSF; JSF user‑interface components may be selected from a component palette and added to a J2EE application.

What This Book Covers

In Chapter 1 we discuss the JDBC 4.0 specification. We discuss the commonly used interfaces and classes in the JDBC API. We also discuss the new features in JDBC 4.0 specification.

InChapter 2 we configure JDBC in JDeveloper IDE. JDeveloper provides a built-in library for the Oracle database and may be configured with third-party databases also. We connect to MySQL database using the JDBC 4.0 driver for MySQL. We also discuss connection pooling and data sources and the new connection pooling and statement pooling features in JDBC 4.0. We run a web application in the embedded OC4J server to connect with the MySQL database and retrieve and display data from the database.

InChapter 3 we discuss the JavaServer Pages Standard Tag Library (JSTL) SQL tags. JDeveloper 10.1.3 provides a Component Palette for JSTL SQL tags. We create a database table, add data to the database table, update the database table, and query the database table, all with the JSTL SQL tag library.

InChapter 4, we discuss configuring JDBC in JBoss Application Server, one of the most commonly used open-source J2EE application server. We develop a web application to connect to MySQL database, and retrieve and display data from the database, in JDeveloper and deploy the web application to JBoss server. We also discuss the JDBC 4.0 version of the web application. We configure data sources in JBoss with Oracle database, MySQL database, DB2 database, PostgreSQL database, and SQL Server.

InChapter 5 we configure JDBC in BEA's WebLogic Server 9.x. WebLogic Server 9 provides some new JDBC features such as additional connection pool properties, which improve data source performance, and support for multi-data sources. We configure a data source with Oracle database. We also develop a web application to retrieve and display data from Oracle database in JDeveloper and deploy the web application to WebLogic server. We also discuss the JDBC 4.0 version of the web application.

InChapter 6 we configure JDBC in IBM's WebSphere application server. WebSphere has a built-in support to configure a JDBC Provider and data source with commonly used databases. We configure a JDBC Provider and data source with IBM's DB2 UDB database. We also develop a web application in JDeveloper to connect with IBM's DB2 UDB database and retrieve and display data from the database. We run the web application in WebSphere Application Server. We also discuss the JDBC 4.0 version of the web application.

InChapter 7, we discuss Oracle's XML SQL Utility (XSU) to map an XML document to a database table and map a database table to an XML document. We also update and delete data in the database using the XML SQL Utility. We develop the XSU application in JDeveloper using the JDBC 4.0 driver for Oracle database.

InChapter 8, we discuss the XSQL Pages Publishing Framework support in JDeveloper 10.1.3. We generate an XML document using an SQL query with XSQL. We also transform the output from an XSQL query using Extensible Stylesheet Language Transformations (XSLT). We also discuss the JDBC 4.0 features that may be availed of in a XSQL application.

InChapter 9, we discuss Oracle JDBC's implementation of a new feature in JDBC 3.0 specification, Web RowSet. A Web RowSet object is an XML representation of a RowSet, which is a container for ResultSet data that may operate without being connected to the data source. Oracle Web RowSet is Oracle database 10g driver's implementation of Web RowSet. We develop an Oracle Web RowSet web application in JDeveloper to create, read, update, and delete a row in Oracle database. We also discuss the JDBC 4.0 version of the Oracle Web RowSet web application.

In Chapter 10 we create a JSF Data Table from Oracle database in JDeveloper. We display database data in a JSF data table using a static SQL query and a dynamically specified SQL query. We also discuss the JDBC 4.0 version of the JSF application to create a data table.

In Chapter 11, we discuss another JSF UI Component, Panel Grid, to display and update database data. We also use JSF validators and converters to convert and validate input data being stored in a database. We develop the JSF Panel Grid application in JDeveloper and also discuss the JDBC 4.0 version of the Panel Grid application.

In Chapter 12, we develop a PDF report and an Excel spreadsheet report with JasperReports reporting tool using JDBC to retrieve data for the report from a database. We develop the JasperReports web application in JDeveloper and also discuss the JDBC 4.0 version of the web application.

In Chapter 13, we create an Excel spreadsheet from database data using the Apache POI HSSF library. We create the report in JDeveloper using JDeveloper's built-in support to connect with a database. We also discuss the JDBC 4.0 version of the Apache POI application.

In Chapter 14, we discuss Business Component for Java (BC4J) layer of Oracle's Application Developer Framework (ADF). Business Components are based on JDBC and consist of view objects, entity objects, and application modules. We develop a web application using the Oracle ADF Model and Business Components API in JDeveloper.

In Chapter 15, we discuss Hibernate, an object/relational persistence and query service for Java. We create a database table, add data to the table, retrieve data from the table, update data in the table and delete table data, all using Hibernate. We will develop the Hibernate application in JDeveloper.

Who is This Book for

This book is for J2EE developers. Most J2EE applications have a database component and the book is specially suited for database-based J2EE development.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

There are three styles for code. Code words in text are shown as follows: "A managed-data-source element is added to the data-sources.xml file."

A block of code will be set as follows:

<resource-ref> <res-ref-name>jdbc/OracleDataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>

Any command-line input and output is written as follows:

CREATE TABLE OE.Catalog(Journal VARCHAR(25), Publisher Varchar(25), Edition VARCHAR(25), Title Varchar(45), Author Varchar(25));

New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: " In the Create Project window specify a Project Name and click on Next".

Note

Important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book

Visit http://www.packtpub.com/files/code/4305_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books — maybe a mistake in text or code — we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Questions

You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.

Connection Interface

The Connection interface represents a connection with the database. SQL statements may be run in a connection session by using a Statement object. A Connection object is in auto-commit mode, by default. In the auto-commit mode, changes are committed to the database after an SQL statement is executed. The auto-commit mode can be modified by calling the setAutoCommit(boolean autoCommit) method. For example, auto-commit may be set to false :

connection.setAutoCommit(false);

If auto-commit is set to false, it would be required to commit changes by calling the commit() method:

connection.commit();

A Connection object can be set to read-only by calling the setReadOnly() method:

connection.setReadOnly(true);

If a Connection object is not required, close the connection by calling the close() method:

connection.close();

The following table discusses the methods in JDBC 4.0 that have been added to the Connection interface.

Method

Description

createArrayOf()

Creates a java.sql.Array object. java.sql.Array is the Java mapping for the SQL data type, ARRAY. The SQL3 data type ARRAY stores an array in a column.

createBlob()

Creates a Blob object.

createClob()

Creates a Clob object.

createNClob()

Creates an NClob object.

createSQLXML()

Creates a SQLXML object.

createStruct()

Creates a Struct object.

isValid()

Tests the validity of a connection.

getClientInfo()

Overloaded method returns a client info property, or a list of client info properties. Client info represents information, such as user name and application name about the client.

setClientInfo()

Overloaded method sets client info.

Transactions

A transaction is a group of one or more statements run as a unit. If the default value of auto-commit is set to true, then each Statement that would be run represents a transaction. After each statement is run, changes to the database are made with the auto-commit set to true. Set the auto-commit to false, if a developer requires a group of statements to be run together. Changes to the database are not made till each of the statement has run. If auto-commit is set to false, the changes to the database are committed with the commit() method. The commit() method commits the SQL statements run after the previous commit to the database was made. The group of statements run between two consecutive commits to the database represents a transaction. The rollback() method rolls back the changes made in the current transaction. A transaction may be required to be rolled back, if an error or a SQLException is generated.

connection.rollback();

While one transaction is modifying a database table, another transaction could be reading from the same table. The type of read can be dirty-read, a non-repeatable read, or a phantom read. A dirty-read occurs when a row has been modified by a transaction, but has not been committed, and is being read by a different transaction. If the transaction that modifies the row rolls back the transaction, then the value retrieved by the second transaction would be erroneous. A non-repeatable transaction occurs when one transaction reads a row while the other transaction modifies it. The first transaction re-reads the row obtaining a different value. A phantom read occurs when one transaction retrieves a result set with a WHERE condition, while the other transaction adds a row that meets the WHERE condition. The first transaction re-runs to generate a result set that has an additional row. The default transaction level can be obtained with the getTransactionLevel() method:

int transactionLevel=connection. getTransactionIsolation();

The different transaction isolation levels are listed in following table:

Transaction Isolation Level

Description

TRANSACTION_NONE

Transactions are not supported.

TRANSACTION_READ_COMMITTED

Dirty-reads cannot be done. Non-repeatable reads and phantom reads can be done.

TRANSACTION_REPEATABLE_READ

Dirty reads and non-repeatable reads cannot be done. Phantom reads can be done.

TRANSACTION_SERIALIZABLE

Dirty-reads, non-repeatable reads and phantom reads cannot be done.

The transaction isolation level can be set with the setTransactionIsolation(int level) method:

connection.setTransactionIsolation(level);

Savepoint Interface

Savepoint is a new interface in JDBC 3.0 specification. A Savepoint is a point within a transaction up to which the changes made in the transaction are rolled back, if the transaction is rolled back with the rollback() method. All changes before the savepoint are implemented when a transaction is rolled back. A savepoint is set with the overloaded setSavepoint() method:

Savepoint savepoint=connection.setSavepoint(); Savepoint savepoint=connection.setSavepoint("savepointName");

The getSavepointId() method returns the savepoint id, and the getSavepointName() method returns the savepoint name.

Statement Interface

The Statement interface runs SQL statements in a database and returns the result sets. A Statement object is obtained from a Connection object with the overloaded createStatement() method. Before enumerating the different createStatement() methods, we will discuss about the result set type, result set concurrency, and result set holdability. There are three result set types:

TYPE_FORWARD_ONLYTYPE_SCROLL_INSENSITIVETYPE_SCROLL_SENSITIVE

The TYPE_FORWARD_ONLY result set is not scrollable. Its cursor moves only in the forward direction. The rows in the result set satisfies the query, either at the time when the query is executed, or when the rows are retrieved.

The TYPE_SCROLL_INSENSITIVE result set is scrollable. The rows in the result set do not reflect the changes made in the database. The rows in the result set satisfy the query, either at the time when the query is executed, or when the rows are retrieved.

The TYPE_SCROLL_SENSITIVE result set is scrollable, and reflects the changes made to the database while the result set is open.

Result set concurrency specifies the level of updatability. There are two concurrency levels:

CONCUR_READ_ONLYCONCUR_UPDATABLE

CONCUR_READ_ONLY is the default concurrency level. The CONCUR_READ_ONLY concurrency specifies a result set that is not updatable, and CONCUR_UPDATABLE concurrency specifies a result set that is updatable.

Holdability specifies that the result set objects are to be kept open when the commit() method is invoked. There are two holdability values:

HOLD_CURSORS_OVER_COMMITCLOSE_CURSORS_AT_COMMIT

If HOLD_CURSORS_OVER_COMMIT is specified, the result set objects (that is cursors) are kept open after the commit() method is called. If CLOSE_CURSORS_AT_COMMIT is specified, the result set objects are closed at the commit() method.

The different createStatement() methods, which are used to create a Statement object from a Connection object are discussed in following table:

Create Statement Method

Description

createStatement()

A Statement object is created with result set of type TYPE_FORWARD_ONLY, and of concurrency CONCUR_READ_ONLY.

createStatement(int resultSetType, int resultSetConcurrency)

A Statement object is created with the specified result set type and result set concurrency. Implementation dependent, resultSetHoldability is used.

createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)

A Statement object is created with the specified result set type, concurrency, and holdability.

Different execute() methods are available to run an SQL statement that may return multiple results. The execute(String sqlStatement) method runs an SQL statement and returns a boolean, which indicates whether the first result is a ResultSet object, or an update count. If true is returned, the first result is a ResultSet object. If false is returned, the first result is an update count. If the first result is a ResultSet object, then the ResultSet object can be obtained with the getResultSet() method. If the first result is an update count, then the update count can be obtained with the getUpdateCount() method:

Statement stmt=connection.createStatement(); boolean resultType=stmt.execute("SQL Statement"); if(resultType==true) ResultSet resultSet=stmt.getResultSet(); else int updateCount=stmt.getUpdateCount();

Multiple results can be returned by the execute() method. To obtain additional results, invoke the getMoreResults() method. The return value of the getMoreResults() method is similar to that of the execute() method. JDBC 3.0 introduced the getMoreResults(int) method to specify whether the current result set should be closed before opening a new result set. The getMoreResults(int) method parameter value can be CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, or KEEP_CURRENT_RESULT. If the parameter value is CLOSE_ALL_RESULTS, then all the previously opened ResultSet objects would be closed. If the value is CLOSE_CURRENT_RESULT, only the current ResultSet object is closed. If the value is KEEP_CURRENT_RESULT, the current ResultSet object is not closed.

The setQueryTimeout(int) method specifies the timeout, in seconds, for a Statement object to execute. The executeQuery(String sql) executes an SQL query and returns a single ResultSet object. The executeUpdate(String sql) method executes an SQL statement, which is either a DML (INSERT, UPDATE, or DELETE) statement or a DDL statement. If the SQL string is a DML statement, the executeUpate(String) method returns the number of rows modified. If the SQL string is a DDL statement, the method returns the value, "0". SQL statements can also be run in a batch with the executeBatch() method. Add SQL commands to run a batch with the addBatch(String sql) method:

stmt.addBatch("SQL command"); stmt.executeBatch();

The executeBatch() method returns an int[] value of update counts. The batch SQL commands can be cleared with the clearBatch() method. If a Statement object is not being used, it is closed automatically. It is recommended to close the Statement object with the close() method:

stmt.close();

When a Statement object is closed, the database and the JDBC resources associated with that object are also closed. Further, the ResultSet object associated with the Statement object is also closed.

In JDBC 4.0, the new methods discussed in following table have been added to the Statement interface:

Method

Description

isClosed()

Tests, if the Statement object has been closed.

isPoolable()

Tests, if the Statement object is poolable.

setPoolable()

Sets the Statement object as poolable. By default, a Statement object is not set to poolable. The method is only a hint to the statement pooling implementation. Statement pooling provides a better management for statement pooling resources.

ResultSet Interface

A ResultSet is a table of data, which is a database result set. The result set types, concurrency and holdability were discussed in the previous section. A ResultSet object can be created to scroll, update, and keep the cursors open, when a commit is done:

Statement stmt=connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT); ResultSet rs=stmt.execute("sql");

A ResultSet has a cursor, which points to the current row. Initially, the cursor points before the first row. The next() method moves the cursor to the next row. The previous() method shifts the cursor to the previous row. The ResultSet interface provides different methods to position the cursor. If the ResultSet is scrollable, then the result set type is TYPE_SCROLL_INSENSITIVE, or TYPE_SCROLL_SENSITIVE and the cursor can be shifted to a specified position. Some of the methods to position a ResultSet cursor are listed in following table:

ResultSet Method

Description

absolute(int row)

Positions the cursor to the specified row. Index for the First row is 1. If the index is a - ve number, then the cursor is positioned with respect to the end of the result set. -1 index, positions the cursor to the last row. If the index is more than the number of rows in the ResultSet, then the cursor is positioned at the end of the ResultSet. If the -ve index is less than the number of rows, then the cursor is positioned before the first row. The method returns the value as true, if the cursor is in the ResultSet.

afterLast()

Positions the cursor after the last row.

beforeFirst()

Positions the cursor before the first row. SQLException is generated, if the ResultSet is TYPE_FORWARD_ONLY

first()

Positions the cursor on the first row in the ResultSet. Returns the value as true, if cursor is on a valid row.

last()

Positions the cursor on the last row in the ResultSet.

relative(int rows)

Positions the cursor to a relative number of rows from the current row. If the relative position is before or after the current row, the cursor is positioned before or after the current row.

For an updatable result set, the method moveToInsertRow() moves the cursor to the insert row, which is a buffer, to insert a new row. The cursor can be shifted back to the current row with the method, moveToCurrentRow(). The ResultSet interface has methods, which are used to obtain the position of the cursor, and are listed in following table:

Method Name

Description

isAfterLast()

Returns true, if the cursor's position is after the last row.

isFirst()

Returns true, if the cursor's position is in the first row.

isLast()

Returns true, if the cursor's position is in the last row.

isBeforeFirst()

Returns true, if the cursor's position is before the first row.

The ResultSet column values are obtained with the help of getter methods. The ResultSet interface has a 'getter' method for each of the Java data types that map to the database data type. If the database data type is mappable to the Java data type, the Java data type is returned. A getter method with a column index position and column name are included for each of the data types. The getter method with the column index position is more efficient. An int column value is retrieved with the index position, and a String column value is retrieved with the column name as follows:

ResultSet rs; Int intColumnValue=rs.getInt(1); String stringColumnValue=rs.getString("column name");

The ResultSet interface has updater methods to update column values in a row. An 'updater' method is included for each of the Java data types that map to the database data type. If the ResultSet is updatable, then the column values in a row can be updated, or a new row can be added. To update a row, move the cursor to the row to be updated. For example, shift the cursor to the tenth row. Update a column value with an updater method. For example, update a String column, column1 to the value col1val. Also update the row in the database:

rs.absolue(10); rs.updateString("column1", "col1val"); rs.updateRow();

The method updateRow() updates the database. To add a new row, shift the cursor to the insert row with the moveToInsertRow() method. Add column values with the updater methods, and insert a row in the database with the insertRow() method. Shift the cursor to the current row with the moveToCurrentRow() method:

rs.moveToInsertRow(); rs.updateString(1, "JDBC4.0"); rs.updateInt(2,16); rs.updateBoolean(3, true); rs.insertRow(); rs.moveToCurrentRow();

The current row in a ResultSet can be deleted with the deleteRow() method. A ResultSet object is automatically closed and the associated resources are released when the Statement object that had created the ResultSet object is being closed. However, it is recommended to close the ResultSet object using the close() method.

rs.close();

In JDBC 4.0, the methods discussed in following table have been added to the ResultSet interface:

Method

Description

getHoldability()

Returns the holdability of the ResultSet object.

getRowId()

Overloaded method returns the row id of the specified column.

updateRowId()

Overloaded method updates the row id for the specified RowId of an object.

getNClob()

Overloaded method returns the specified column as an NClob object.

isClosed()

Returns a Boolean value to indicate if the ResultSet object is closed.

getNString()

Overloaded method returns the specified column as a String object, which is used with NCHAR, NVARCHAR and LONGNVARCHAR columns.

getNCharacterStream()

Overloaded method returns the specified column value as a java.io.Reader object, which is used with NCHAR, NVARCHAR and LONGNVARCHAR columns.

updateNString()

Overloaded method updates the specified column with the specified String value, which is used with NCHAR, NVARCHAR and LONGNVARCHAR columns.

updateNCharacterStream()

Overloaded method updates the specified column with the specified character stream, and the specified String value. It is used with NCHAR, NVARCHAR and LONGNVARCHAR columns.

getSQLXML()

Overloaded method returns the specified column as an SQLXML object. SQLXML Java data type is discussed in a later section, in this chapter.

updateSQLXML()

Overloaded method updates the specified column with the specified SQLXML value.

updateNClob()

Overloaded method updates the specified column with the specified Reader object.

The updateObject() method in the ResultSet interface has been modified to support the new data types, NClob and SQLXML in JDBC 4.0. The updater methods in the table do not update the underlying database. To update the database, the insertRow() or updateRow() method is required to be invoked.

JDBC Exceptions

SQLException is the main Exception that is generated in a JDBC application. The detail of an SQL exception can be obtained from an SQLException object using the SQLException methods, some of which are discussed in following table:

Method

Description

getMessage()

Returns a textual description of the error.

getSQLState()

Returns a SQLState for the SQLException.

getErrorCode()

Returns the implementation-specific error code for the SQLException object.

getCause()

Returns the cause of the SQLException or null, if the cause is not specified or not known.

getNextException()

Returns an exception chained to the SQLException. All the chained exceptions can be retrieved by invoking the getNextException() method recursively. Returns null, if no chained exception occurs.

getMessage()

Returns a textual description of the error.

When an SQLException occurs, it is likely that one or more SQLExceptions chained to it, have also occurred. The chained exceptions can be retrieved by invoking the getNextException() method recursively, until the method returns null. The cause of an SQLException can be retrieved using the getCause()