Among the many new features and improvements that Java SE 6 offers, it is worth mentioning that the JDBC version that provides the database access mechanism for Java programs has been upgraded to 4.0, a JSR-221-coded version that provides more convenient code authoring mechanisms and flexibility, and supports more data types . In this article, we will explore the new features and improvements of JDBC 4.0 from the perspective of ease-of-use and flexibility in coding.
New features of JDBC 4.0
The JDBC 4.0 documentation lists 20 improvements and new features, ranging in size. This article can not do all the details, the author according to its functional characteristics and application fields will be divided into the following four categories:
1. Drive and connection management
2. Exception handling
3. Data type Support
4. Changes to the API
The following four types of expansion are described in detail:
Drive and connection Management
Drive and connection usage and result set management-significant changes have taken place in many areas of JDBC
Connecting to a database makes it easier
If you've ever had a JDBC development experience, I'm sure you also have a list of jobs that you must have to establish a database connection. The first item in the list loads an appropriate driver. Have you ever thought that this step should be improved? Done in this version of JDBC. You no longer have to explicitly load the class.forname. When your program first tries to connect to the database, DriverManager automatically loads the CLASSPATH that is driven to the current app. This is a relatively large change for JDBC.
Although DriverManager can now automatically load the driver, establishing a DataSource object is still the recommended way to get a connection. DataSource is more transparent and flexible because it can point data sources to different databases in the configuration. This makes it possible to access another DB instance without changing any of the existing lines of code, or even the database drivers are completely different.
The use of ResultSet becomes more flexible
The hierarchical structure of the ResultSet interface currently provides some new mechanisms for programmatic flexibility. RowSet Sub-interface scrolling, ResultSet that can be submitted and edited offline. The Webrowset sub-interface provides the ability to fetch data from a database table and serialize it to an XML document, or to parse the XML into result set. Although the previous version of JDBC also provided the RowSet interface hierarchy, the current version is more supported for SQLXML data types (discussed later), and these features are much easier and more flexible for JDBC programming.
More APIs are available
This version of JDBC provides additional APIs for accessing the new features of sql:2003. In addition, JDBC adds a number of ways to better manipulate the data.
Now let's look at some code and discuss the output of the Example1 class below. It will connect to the embedded Apache Derby database and display the output results on the console. Although JDBC 4.0 has been available for several months, the author finds that only Apache Derby provides drivers that support the JDBC 4.0 specification (as of March 2007). All of the examples in this article were developed using JDK 1.6 and Apache Derby database 10.2.2.0.
public class Example1 {
public static void Main (string[] args) {
...
String dbName = "example1";
String tableName = "STU1";
ds = new EmbeddedDataSource40 ();
Ds.setdatabasename (DbName);
String Connectionurl = "Jdbc:derby:" +dbname+ "; Create=true";
try {
con = ds.getconnection ();
stmt = Con.createstatement ();
rs = Stmt.executequery ("SELECT * from" +tablename);
int colcount= rs.getmetadata (). getColumnCount ();
for (int j=0; j< ColCount; j + +) {
System.out.print (Rs.getmetadata (). getColumnName (j+1)
+ "\ T");
}
while (Rs.next ()) {
System.out.print ("\ n");
for (int i = 0; i < ColCount; i++) {
System.out.print (rs.getstring (i + 1) + "\ T");
}
}
} catch (SQLException e) {
E.printstacktrace ();
}
finally{
Close connections
}
}
}
If you have data in the STU1 table in the example1 database, compiling and running Example1.java will get the following output from the console:
ID NAME COURSE
1001 John Doe Statistics
1002 Jack McDonalds Linear Algebra
If you want to see how drivermanager automatically loads the JDBC driver, you can replace the following: Con=ds.getconnection () in Example1 with: Con=drivermanager.getconnection (connecti Onurl). The class will produce the same output. As you can see, it is no longer necessary to explicitly call Class.forName ().
Exception handling
How can you tell if a Java program is robust or not? In my opinion, the exception handling mechanism is one of the important considerations. A robust Java program can handle exceptions well and give the program the ability to recover when an exception occurs. A non-robust program will result in incorrect output and even crash the entire application!
JDBC 4.0 adds some simple and powerful exception handling mechanisms, which are worth mentioning is the chain exception, if the exception chain exists, you can apply the enhanced For-each loop to get the exception chain. The local structure of the following Example2 class shows how to apply this new method to handle chained exceptions:
public class Example2 {
public static void Main (string[] args) {
String DbName = "Example";
String tableName = "Student4";
try {
con = ds.getconnection ();
stmt = Con.createstatement ();
rs = Stmt.executequery ("SELECT * from" + tableName);
} catch (SQLException sx) {
for (Throwable e:sx) {
System.err.println ("Error encountered:" + e);
}
}
finally{
Close connections
}
}
}
Run Example2.java, and note that STUDENT4 is not a table that actually exists in the database. A chained exception will be generated in the following calls:
rs = Stmt.executequery ("SELECT * from" + tableName);
In practical applications, these anomalies need to be captured, detected and processed accordingly. In this case, the author only outputs it on the console. The following is the output code:
for (Throwable e:sx) {
System.err.println ("Error encountered:" + e);
}
The following is the result of the class Example2 output:
Error encountered:java.sql.SQLSyntaxErrorException:
Table/view ' STUDENT4 ' does not exist.
Error encountered:java.sql.SQLException:
Table/view ' STUDENT4 ' does not exist.
Exception in thread "main" java.lang.NullPointerException
At ex. Examlpe2.main (examlpe2.java:51)
By applying JDBC 4.0, you don't need much code now to get and traverse the chain of exceptions. In previous versions, when you traversed the chain of exceptions, you had to call the Getnextexception method manually to get the same effect.
Supported data types
This version of JDBC adds some new data types and provides better support for some of the other data types. I am delighted that XML has been formally supported, and a new interface has been created in this version: SQLXML. In my opinion, this interface deserves a separate chapter for its discussion:
Support for SQLXML and XML
SQLXML is the representation of XML data types in Java in SQL, which is the built-in data type used in SQL to represent XML data in a table. By default, the JDBC driver points the SQLXML pointer to the XML data instead of the data itself. The SQLXML object is stable in the transaction in which it was created.
In the following Example3 class, I will show you how to apply SQLXML and update the table data in the current connection.
public class Example3 {
public static void Main (string[] args) {
...
con = ds.getconnection ();
SQLXML sx= con.createsqlxml ();
Sx.setstring ("Math is Fun");
String PSX = "INSERT INTO" +tablename+
(ID, textbook) VALUES (?,?) ";
PreparedStatement pstmt = con.preparestatement (PSX);
Pstmt.setstring (1, "1000");
Pstmt.setsqlxml (2,SX);
Pstmt.executeupdate ();
...
}
}
This example illustrates the simplest scenario that you can apply. If we go further, things will become much more interesting. But before we go into the discussion, let me tell you about running Example3.java. The result. Unfortunately, I was unable to get to the SQLXML object and got the following disappointing output:
Java.sql.SQLFeatureNotSupportedException:Feature not
Implemented:no details.
At org.apache.derby.impl.jdbc.SQLExceptionFactory40.
Getsqlexception (Unknown Source)
... ... ... ...
At ex. Example3.main (example3.java:62)
It appears that Apache Derby does not provide a way to get SQLXML objects from Connection. But at least you can see what I'm trying to implement in class Example3: I want to insert a new row of data: The ID column value is textbook column (S qlxml type) inserted into Math is fun.
The author ends the discussion of SQLXML with the following code snippet, which reads the XML value from the database and translates it into a Document object.
SQLXML SQLXML = rs.getsqlxml (column);
InputStream Binarystream = Sqlxml.getbinarystream ();
Documentbuilder parser =
Documentbuilderfactory.newinstance (). Newdocumentbuilder ();
Document doc = Parser.parse (binarystream);
Is it not an exciting thing to convert the value of a column directly into an XML document? I think this feature is very good.
ROWID Data types
SQL ROWID uniquely identifies a row in a data table and is the quickest way to access the row, and this version adds the ROWID interface to provide support for ROWID SQL data types in Java classes.
Enhancements for large object type support
JDBC version 2 provides support for large SQL objects such as: CLOB, blob, array, and Struct:clob, blob, array, and Struct for adding related interfaces. A number of new methods for accessing these objects have been added to this version of JDBC. I will discuss this in detail in the API change section.
Support for National Character Set (NCS) conversions
SQL:2003 provides support for the following SQL data types: NCHAR, NVARCHAR, Longnvarchar, and NCLOB. Its function is similar to CHAR, VARCHAR, LongVarChar, and CLOB, except that the text of these types is encoded with NCS. If you need a lot of character processing, you might prefer the NCS data type rather than the normal data type. This version of JDBC provides an enhanced API for NCS support.
A number of setter and updater methods have been added to the PreparedStatement, CallableStatement, and ResultSet interfaces to support NCS conversions. such as methods Setnstring, Setncharacterstream, and Setnclob and so on.
Read and write methods are added to the Sqlinput and SQLOutput interfaces to support T NClob and nstring objects.
API changes
The biggest change in JDBC 4.0 comes from the API, which is briefly described in this section.
Array
The array interface adds a free method to release the array object and the resources it holds.
Connection and Pooledconnection
The Connection interface now offers a range of methods for creating large objects such as Createclob, Createblob, and so on. There are also methods for getter and setter overloading of client information, and verifying the correctness of the current connection.
The Pooledconnection interface currently provides Addstatementeventlistener and Removestatementeventlistener two methods to register and unregister the Statementeventlistener interface , this interface is newly introduced in this version of JDBC. An instance of this interface will get the change of PreparedStatement s in the S tatement pool. For example, after registration, when the driver calls the Statementclosed method, all Statementeventlistener will get a notification that statement has been closed.
DatabaseMetaData
Different relational databases tend to support different features and implement these features in different ways, and may be in different data types. This can lead to portability issues because, depending on the implementation, the code cannot be guaranteed to execute correctly on all relational databases. Such a problem can be solved to some extent by the information obtained by this interface. For example, if you are writing a code that creates a table by passing in an SQL statement. You may want to know what data types are available in the CREATE TABLE statement, and you can call the GetTypeInfo method in that interface.
This version of JDBC adds some ways to get information. In Example4, I'll show you how to get a list of database structures that satisfy a pattern in a piece of code:
con = ds.getconnection ();
DatabaseMetaData DMD = Con.getmetadata ();
Rs=dmd.getschemas ("Table_cat", "sys%");
Iterate over the RS and print to console
First, by calling Dmd.getcatalogs and traversing the result set, a unique value is obtained: Table_cat. Then, by calling Rs=dmd.getschemas ("Table_cat", "sys%"), the database and table structure starting with SYS are obtained. The following are the results I get:
SYS
SYSCAT
Syscs_diag
Syscs_util
Sysfun
SYSIBM
Sysproc
SYSSTAT
Scalar function Support
A scalar function operates a predefined set of input data and returns the result. For example, the scalar function calls ABS (number) to return the absolute value of number. These scalar functions can be used as part of a SQL string. This version of JDBC requires that when the dependent relational database supports the following features: Char_length, Character_length, Current_date, Current_time, Current_timestamp, EXTRACT, Octet_length, and POSITION, drivers must implement these features.
Statement, PreparedStatement, and CallableStatement
The Statement interface currently provides the IsClosed method to determine whether Statement is closed, setpoolable to set whether it can be pooled, and ispoolable to detect the current pooled state.
The PreparedStatement and CallableStatement interfaces now provide more ways to insert large objects by using InputStream, Reader, and so on.
Wrapper
This version of the API adds a new Wrapper interface to provide a way to access instances of resources, which may be schema-based considerations. The Wrapper mode is implemented by many JDBC drivers to provide applications that rely on specific data sources beyond the JDBC API. The main purpose of this interface is to provide vendor-related functionality. You can obtain an instance of an interface implementation to a database connection by calling the Unwrap method. Because this is a heavyweight operation, you should first call the Iswrapperfor method to detect if the current instance is an indirect or direct wapper of some implementation before using it.
The ability to give a program example is of course the best, but Apache Derby reference manual L states: "JDBC 4.0 introduces the concept of the wrapped JDBC object ... For Derby, this doesn't make sense for Derby, because Derby does not do extensions outside of the norm. "So it seems that this attempt has become unnecessary!"
Reproduced in: http://fsh430623.iteye.com/blog/1044073
JDBC4.0 new Features