JDBC API Description
-
package java.sql description
-
What the JDBCTM 4.2 API Includes
-
Versions
-
What the
java.sqlPackage Contains- Making a connection with a database via the
DriverManagerfacility - Sending SQL statements to a database
- Retrieving and updating the results of a query
- Standard mappings for SQL types to classes and interfaces in the Java programming language
- Custom mapping an SQL user-defined type (UDT) to a class in the Java programming language
- Metadata
- Exceptions
- Making a connection with a database via the
-
java.sqlandjavax.sqlFeatures Introduced in the JDBC 4.2 API -
java.sqlandjavax.sqlFeatures Introduced in the JDBC 4.1 API -
java.sqlandjavax.sqlFeatures Introduced in the JDBC 4.0 API -
java.sqlandjavax.sqlFeatures Introduced in the JDBC 3.0 API -
java.sqlFeatures Introduced in the JDBC 2.1 Core API -
javax.sqlFeatures Introduced in the JDBC 2.0 Optional Package API -
Custom Mapping of UDTs
-
-
Package javax.sql Description
-
Using a
DataSourceObject to Make a Connection -
Connection Pooling and Statement Pooling
-
Distributed Transactions
-
Rowsets
- Event Notification
- Metadata
- The Reader/Writer Facility
-
Package java.sql Description
javax.sql.RowSet group of interfaces, can be customized to use and update data from a spread sheet, flat file, or any other tabular data source.
What the JDBCTM 4.2 API Includes
The JDBCTM 4.2 API includes both thejava.sql package, referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional Package API. This complete JDBC API is included in the JavaTM Standard Edition (Java SETM), version 7. The javax.sql package extends the functionality of the JDBC API from a client-side API to a server-side API, and it is an essential part of the JavaTM Enterprise Edition (Java EETM) technology.
Versions
The JDBC 4.2 API incorporates all of the previous JDBC API versions:- The JDBC 4.1 API
- The JDBC 4.0 API
- The JDBC 3.0 API
- The JDBC 2.1 core API
- The JDBC 2.0 Optional Package API
(Note that the JDBC 2.1 core API and the JDBC 2.0 Optional Package API together are referred to as the JDBC 2.0 API.) - The JDBC 1.2 API
- The JDBC 1.0 API
Classes, interfaces, methods, fields, constructors, and exceptions have the following "since" tags that indicate when they were introduced into the Java platform. When these "since" tags are used in JavadocTM comments for the JDBC API, they indicate the following:
- Since 1.8 -- new in the JDBC 4.2 API and part of the Java SE platform, version 8
- Since 1.7 -- new in the JDBC 4.1 API and part of the Java SE platform, version 7
- Since 1.6 -- new in the JDBC 4.0 API and part of the Java SE platform, version 6
- Since 1.4 -- new in the JDBC 3.0 API and part of the J2SE platform, version 1.4
- Since 1.2 -- new in the JDBC 2.0 API and part of the J2SE platform, version 1.2
- Since 1.1 or no "since" tag -- in the original JDBC 1.0 API and part of the JDKTM, version 1.1
NOTE: Many of the new features are optional; consequently, there is some variation in drivers and the features they support. Always check your driver's documentation to see whether it supports a feature before you try to use it.
NOTE: The class SQLPermission was added in the JavaTM 2 SDK, Standard Edition, version 1.3 release. This class is used to prevent unauthorized access to the logging stream associated with the DriverManager, which may contain information such as table names, column data, and so on.
What the java.sql Package Contains
The java.sql package contains API for the following:
- Making a connection with a database via the
DriverManagerfacilityDriverManagerclass -- makes a connection with a driverSQLPermissionclass -- provides permission when code running within a Security Manager, such as an applet, attempts to set up a logging stream through theDriverManagerDriverinterface -- provides the API for registering and connecting drivers based on JDBC technology ("JDBC drivers"); generally used only by theDriverManagerclassDriverPropertyInfoclass -- provides properties for a JDBC driver; not used by the general user
- Sending SQL statements to a database
Statement-- used to send basic SQL statementsPreparedStatement-- used to send prepared statements or basic SQL statements (derived fromStatement)CallableStatement-- used to call database stored procedures (derived fromPreparedStatement)Connectioninterface -- provides methods for creating statements and managing connections and their propertiesSavepoint-- provides savepoints in a transaction
- Retrieving and updating the results of a query
ResultSetinterface
- Standard mappings for SQL types to classes and interfaces in the Java programming language
Arrayinterface -- mapping for SQLARRAYBlobinterface -- mapping for SQLBLOBClobinterface -- mapping for SQLCLOBDateclass -- mapping for SQLDATENClobinterface -- mapping for SQLNCLOBRefinterface -- mapping for SQLREFRowIdinterface -- mapping for SQLROWIDStructinterface -- mapping for SQLSTRUCTSQLXMLinterface -- mapping for SQLXMLTimeclass -- mapping for SQLTIMETimestampclass -- mapping for SQLTIMESTAMPTypesclass -- provides constants for SQL types
- Custom mapping an SQL user-defined type (UDT) to a class in the Java programming language
SQLDatainterface -- specifies the mapping of a UDT to an instance of this classSQLInputinterface -- provides methods for reading UDT attributes from a streamSQLOutputinterface -- provides methods for writing UDT attributes back to a stream
- Metadata
DatabaseMetaDatainterface -- provides information about the databaseResultSetMetaDatainterface -- provides information about the columns of aResultSetobjectParameterMetaDatainterface -- provides information about the parameters toPreparedStatementcommands
- Exceptions
SQLException-- thrown by most methods when there is a problem accessing data and by some methods for other reasonsSQLWarning-- thrown to indicate a warningDataTruncation-- thrown to indicate that data may have been truncatedBatchUpdateException-- thrown to indicate that not all commands in a batch update executed successfully
java.sql and javax.sql Features Introduced in the JDBC 4.2 API
- Added
JDBCTypeenum andSQLTypeinterface - Support for
REF CURSORSinCallableStatement DatabaseMetaDatamethods to return maximum Logical LOB size and if Ref Cursors are supported- Added support for large update counts
java.sql and javax.sql Features Introduced in the JDBC 4.1 API
- Allow
Connection,ResultSetandStatementobjects to be used with the try-with-resources statement - Supported added to
CallableStatementandResultSetto specify the Java type to convert to via thegetObjectmethod DatabaseMetaDatamethods to return PseudoColumns and if a generated key is always returned- Added support to
Connectionto specify a database schema, abort and timeout a physical connection. - Added support to close a
Statementobject when its dependent objects have been closed - Support for obtaining the parent logger for a
Driver,DataSource,ConnectionPoolDataSourceandXADataSource
java.sql and javax.sql Features Introduced in the JDBC 4.0 API
- auto java.sql.Driver discovery -- no longer need to load a
java.sql.Driverclass viaClass.forName - National Character Set support added
- Support added for the SQL:2003 XML data type
- SQLException enhancements -- Added support for cause chaining; New SQLExceptions added for common SQLState class value codes
- Enhanced Blob/Clob functionality -- Support provided to create and free a Blob/Clob instance as well as additional methods added to improve accessibility
- Support added for accessing a SQL ROWID
- Support added to allow a JDBC application to access an instance of a JDBC resource that has been wrapped by a vendor, usually in an application server or connection pooling environment.
- Availability to be notified when a
PreparedStatementthat is associated with aPooledConnectionhas been closed or the driver determines is invalid
java.sql and javax.sql Features Introduced in the JDBC 3.0 API
- Pooled statements -- reuse of statements associated with a pooled connection
- Savepoints -- allow a transaction to be rolled back to a designated savepoint
- Properties defined for
ConnectionPoolDataSource-- specify how connections are to be pooled - Metadata for parameters of a
PreparedStatementobject - Ability to retrieve values from automatically generated columns
- Ability to have multiple
ResultSetobjects returned fromCallableStatementobjects open at the same time - Ability to identify parameters to
CallableStatementobjects by name as well as by index ResultSetholdability -- ability to specify whether cursors should be held open or closed at the end of a transaction- Ability to retrieve and update the SQL structured type instance that a
Refobject references - Ability to programmatically update
BLOB,CLOB,ARRAY, andREFvalues. - Addition of the
java.sql.Types.DATALINKdata type -- allows JDBC drivers access to objects stored outside a data source - Addition of metadata for retrieving SQL type hierarchies
java.sql Features Introduced in the JDBC 2.1 Core API
- Scrollable result sets--using new methods in the
ResultSetinterface that allow the cursor to be moved to a particular row or to a position relative to its current position - Batch updates
- Programmatic updates--using
ResultSetupdater methods - New data types--interfaces mapping the SQL3 data types
- Custom mapping of user-defined types (UDTs)
- Miscellaneous features, including performance hints, the use of character streams, full precision for
java.math.BigDecimalvalues, additional security, and support for time zones in date, time, and timestamp values.
javax.sql Features Introduced in the JDBC 2.0 Optional Package API
- The
DataSourceinterface as a means of making a connection. The Java Naming and Directory InterfaceTM (JNDI) is used for registering aDataSourceobject with a naming service and also for retrieving it. - Pooled connections -- allowing connections to be used and reused
- Distributed transactions -- allowing a transaction to span diverse DBMS servers
RowSettechnology -- providing a convenient means of handling and passing data
Custom Mapping of UDTs
A user-defined type (UDT) defined in SQL can be mapped to a class in the Java programming language. An SQL structured type or an SQLDISTINCT type are the UDTs that may be custom mapped. The following three steps set up a custom mapping:- Defining the SQL structured type or
DISTINCTtype in SQL - Defining the class in the Java programming language to which the SQL UDT will be mapped. This class must implement the
SQLDatainterface. - Making an entry in a
Connectionobject's type map that contains two things:- the fully-qualified SQL name of the UDT
- the
Classobject for the class that implements theSQLDatainterface
When these are in place for a UDT, calling the methods ResultSet.getObject or CallableStatement.getObject on that UDT will automatically retrieve the custom mapping for it. Also, thePreparedStatement.setObject method will automatically map the object back to its SQL type to store it in the data source.
Package javax.sql Description
java.sql package and, as of the version 1.4 release, is included in the Java Platform, Standard Edition (Java SETM). It remains an essential part of the Java Platform, Enterprise Edition (Java EETM).
The javax.sql package provides for the following:
- The
DataSourceinterface as an alternative to theDriverManagerfor establishing a connection with a data source - Connection pooling and Statement pooling
- Distributed transactions
- Rowsets
Applications use the DataSource and RowSet APIs directly, but the connection pooling and distributed transaction APIs are used internally by the middle-tier infrastructure.
Using a DataSource Object to Make a Connection
The javax.sql package provides the preferred way to make a connection with a data source. The DriverManager class, the original mechanism, is still valid, and code using it will continue to run. However, the newer DataSource mechanism is preferred because it offers many advantages over the DriverManager mechanism.
These are the main advantages of using a DataSource object to make a connection:
- Changes can be made to a data source's properties, which means that it is not necessary to make changes in application code when something about the data source or driver changes.
- Connection and Statement pooling and distributed transactions are available through a
DataSourceobject that is implemented to work with the middle-tier infrastructure. Connections made through theDriverManagerdo not have connection and statement pooling or distributed transaction capabilities.
Driver vendors provide DataSource implementations. A particular DataSource object represents a particular physical data source, and each connection the DataSource object creates is a connection to that physical data source.
A logical name for the data source is registered with a naming service that uses the Java Naming and Directory InterfaceTM (JNDI) API, usually by a system administrator or someone performing the duties of a system administrator. An application can retrieve the DataSource object it wants by doing a lookup on the logical name that has been registered for it. The application can then use the DataSource object to create a connection to the physical data source it represents.
A DataSource object can be implemented to work with the middle tier infrastructure so that the connections it produces will be pooled for reuse. An application that uses such a DataSourceimplementation will automatically get a connection that participates in connection pooling. A DataSource object can also be implemented to work with the middle tier infrastructure so that the connections it produces can be used for distributed transactions without any special coding.
Connection Pooling and Statement Pooling
Connections made via aDataSource object that is implemented to work with a middle tier connection pool manager will participate in connection pooling. This can improve performance dramatically because creating new connections is very expensive. Connection pooling allows a connection to be used and reused, thus cutting down substantially on the number of new connections that need to be created.
Connection pooling is totally transparent. It is done automatically in the middle tier of a Java EE configuration, so from an application's viewpoint, no change in code is required. An application simply uses the DataSource.getConnection method to get the pooled connection and uses it the same way it uses any Connection object.
The classes and interfaces used for connection pooling are:
ConnectionPoolDataSourcePooledConnectionConnectionEventConnectionEventListenerStatementEventStatementEventListener
ConnectionPoolDataSource object is called on to create a PooledConnection object, the connection pool manager will register as a ConnectionEventListener object with the new PooledConnection object. When the connection is closed or there is an error, the connection pool manager (being a listener) gets a notification that includes a ConnectionEvent object.
If the connection pool manager supports Statement pooling, for PreparedStatements, which can be determined by invoking the method DatabaseMetaData.supportsStatementPooling, the connection pool manager will register as a StatementEventListener object with the new PooledConnection object. When the PreparedStatement is closed or there is an error, the connection pool manager (being a listener) gets a notification that includes a StatementEvent object.
Distributed Transactions
As with pooled connections, connections made via aDataSource object that is implemented to work with the middle tier infrastructure may participate in distributed transactions. This gives an application the ability to involve data sources on multiple servers in a single transaction.
The classes and interfaces used for distributed transactions are:
XADataSourceXAConnection
The XAConnection interface is derived from the PooledConnection interface, so what applies to a pooled connection also applies to a connection that is part of a distributed transaction. A transaction manager in the middle tier handles everything transparently. The only change in application code is that an application cannot do anything that would interfere with the transaction manager's handling of the transaction. Specifically, an application cannot call the methods Connection.commit or Connection.rollback, and it cannot set the connection to be in auto-commit mode (that is, it cannot call Connection.setAutoCommit(true)).
An application does not need to do anything special to participate in a distributed transaction. It simply creates connections to the data sources it wants to use via theDataSource.getConnection method, just as it normally does. The transaction manager manages the transaction behind the scenes. The XADataSource interface creates XAConnectionobjects, and each XAConnection object creates an XAResource object that the transaction manager uses to manage the connection.
Rowsets
TheRowSet interface works with various other classes and interfaces behind the scenes. These can be grouped into three categories.- Event Notification
RowSetListener
ARowSetobject is a JavaBeansTM component because it has properties and participates in the JavaBeans event notification mechanism. TheRowSetListenerinterface is implemented by a component that wants to be notified about events that occur to a particularRowSetobject. Such a component registers itself as a listener with a rowset via theRowSet.addRowSetListenermethod.When the
RowSetobject changes one of its rows, changes all of it rows, or moves its cursor, it also notifies each listener that is registered with it. The listener reacts by carrying out its implementation of the notification method called on it.RowSetEvent
As part of its internal notification process, aRowSetobject creates an instance ofRowSetEventand passes it to the listener. The listener can use thisRowSetEventobject to find out which rowset had the event.
- Metadata
RowSetMetaData
This interface, derived from theResultSetMetaDatainterface, provides information about the columns in aRowSetobject. An application can useRowSetMetaDatamethods to find out how many columns the rowset contains and what kind of data each column can contain.The
RowSetMetaDatainterface provides methods for setting the information about columns, but an application would not normally use these methods. When an application calls theRowSetmethodexecute, theRowSetobject will contain a new set of rows, and itsRowSetMetaDataobject will have been internally updated to contain information about the new columns.
- The Reader/Writer Facility
ARowSetobject that implements theRowSetInternalinterface can call on theRowSetReaderobject associated with it to populate itself with data. It can also call on theRowSetWriterobject associated with it to write any changes to its rows back to the data source from which it originally got the rows. A rowset that remains connected to its data source does not need to use a reader and writer because it can simply operate on the data source directly.RowSetInternal
By implementing theRowSetInternalinterface, aRowSetobject gets access to its internal state and is able to call on its reader and writer. A rowset keeps track of the values in its current rows and of the values that immediately preceded the current ones, referred to as the original values. A rowset also keeps track of (1) the parameters that have been set for its command and (2) the connection that was passed to it, if any. A rowset uses theRowSetInternalmethods behind the scenes to get access to this information. An application does not normally invoke these methods directly.RowSetReader
A disconnectedRowSetobject that has implemented theRowSetInternalinterface can call on its reader (theRowSetReaderobject associated with it) to populate it with data. When an application calls theRowSet.executemethod, that method calls on the rowset's reader to do much of the work. Implementations can vary widely, but generally a reader makes a connection to the data source, reads data from the data source and populates the rowset with it, and closes the connection. A reader may also update theRowSetMetaDataobject for its rowset. The rowset's internal state is also updated, either by the reader or directly by the methodRowSet.execute.RowSetWriter
A disconnectedRowSetobject that has implemented theRowSetInternalinterface can call on its writer (theRowSetWriterobject associated with it) to write changes back to the underlying data source. Implementations may vary widely, but generally, a writer will do the following:- Make a connection to the data source
- Check to see whether there is a conflict, that is, whether a value that has been changed in the rowset has also been changed in the data source
- Write the new values to the data source if there is no conflict
- Close the connection
The RowSet interface may be implemented in any number of ways, and anyone may write an implementation. Developers are encouraged to use their imaginations in coming up with new ways to use rowsets.
IMPORTANT NOTE: Code that uses API marked "Since 1.6" must be run using a JDBC technology driver that implements the JDBC 4.0 API. You must check your driver documentation to be sure that it implements the particular features you want to use.
作者: 房继诺
出处:http://www.cnblogs.com/f1194361820
版权:本文版权归作者和博客园共有
欢迎转载,转载请需要注明博客出处
技术交流QQ:1194361820,加好友请注明:来自博客园,不要说你是博客园,也可以扫描图像二维码直接加我。

浙公网安备 33010602011771号