JDBC Plate essence Finishing 20051226_JSP programming

Source: Internet
Author: User
Tags connection pooling event listener getmessage instance method rollback savepoint stmt first row

Important NOTE: this part of the article is the owner of the collection from the Internet, and if you think that the content of the document violates your rights, please contact the collation (excelarthur@yahoo.com.cn), and Dev2dev site has nothing to do.

Characteristics of JDBC3.0

1. Database connection pool framework in JDBC3.0 specification
The JDBC3.0 specification provides a framework for supporting the database connection pool, which only specifies how to support the implementation of the connection pool, while the implementation of the JDBC 3.0 specification for the connection pool does not provide relevant provisions. This framework enables developers of different roles to work together to implement database connection pooling.

Through the JDBC3.0 specification can know that the implementation of specific database connection pool can be divided into JDBC driver level and application server level. Any relevant work in the JDBC driver-level implementation is specifically implemented by the JDBC Drvier developer of a particular database vendor, that is, JDBC driver needs to provide support for the database connection pool, as well as a specific implementation of the database connection pool. In the implementation of the database connection pool at the application server level, the JDBC driver developer and application Server developer of a particular database manufacturer together implement the database connection pool (but now most application The mechanisms and specifications for connection pooling implemented by the server manufacturer refer to differences in that the JDBC driver for a particular database vendor provides support for the database connection pool and specific application server vendors provide a concrete implementation of the database connection pool.

The JDBC3.0 specification provides the following classes and interfaces to support the implementation of the database connection pool.

Javax.sql.ConnectionEvent 
javax.sql.ConnectionPoolDataSource 
javax.sql.PooledConnection 
Javax.sql.ConnectionEventListener

In addition to Javax.sql.ConnectionEvent is the class, the other is the interface.

  

Diagram of the JDBC3.0 connection pool framework

This diagram allows you to approximate the location of the relevant interfaces in a typical three-tier environment.

2, the search automatically generated keywords
To address the need to get the value of automatically generated or automatically added keywords, the JDBC 3.0 API now makes it easy to get this value. To determine the value of any resulting keyword, simply specify an optional tag in the Execute () method of the statement to indicate that you are interested in getting the resulting value. The extent of your interest can be statement.return_generated_keys, or it can be statement.no_generated_keys. After executing this statement, the resulting keyword value is obtained by retrieving the ResultSet from the Statement instance method Getgeneratedkeys (), ResultSet contains the columns of each generated keyword, The following example creates a new author and returns the corresponding automatically generated keyword.

..... Statement stmt = Conn.createstatement (); 
Obtain the generated key that results from the query. 
Stmt.executeupdate ("INSERT into authors" + 
"(first_name, last_name)" + 
"VALUES (' Ghq ', ' WXL ')", 
Statement.return_generated_keys); 
ResultSet rs = Stmt.getgeneratedkeys (); 
if (Rs.next ()) { 
//Retrieve the auto generated key (s). 
int key = Rs.getint (); 
}
......

3. Return multiple results
One limitation of the JDBC 2 specification is that at any given time, statements that return multiple results can only open one resultset. As part of the change in the JDBC 3.0 specification, the specification will allow the Statement interface to support multiple open resultsets. However, it is important that the execute () method still closes any ResultSet that was opened in the previous execute () call. Therefore, to support multiple open results, the Statement interface will be preceded by an overloaded Getmoreresults () method. The new method makes an integer tag that specifies the behavior of the previous open ResultSet when the Getresultset () method is invoked. The interface defines the markup as follows:

Close_all_results: When Getmoreresults () is invoked, all previously opened ResultSet objects will be closed.

Close_current_result: When Getmoreresults () is invoked, the current ResultSet object will be closed.

Keep_current_result: When Getmoreresults () is invoked, the current ResultSet object will not be closed.

Here is an example of how to handle multiple open results.

 
..... String Proccall; 
Set the value of Proccall to call a stored procedure. 
... CallableStatement cstmt = Connection.preparecall (proccall); 
int retval = Cstmt.execute (); 
if (retval = = False) { 
//The statement returned a update count, so handle it. 
.. 
} else {//ResultSet 
ResultSet rs1 = Cstmt.getresultset (); 
... retval = Cstmt.getmoreresults (statement.keep_current_result); 
if (retval = = True) { 
ResultSet rs2 = Cstmt.getresultset (); 
Both resultsets are open and ready for use. 
Rs2.next (); 
Rs1.next (); 
.. 
 }}
......

4, the use of savepoint in the transaction
Perhaps the most exciting additional feature of JDBC 3.0 is savepoint. Transaction support in JDBC 2 allows developers to control concurrent access to data, ensuring that persistent data is always in a consistent state. Unfortunately, it is sometimes necessary to have a little more control over the transaction, rather than simply rolling back every change in the current transaction. Under JDBC 3.0, this control can be obtained through savepoint. The SavePoint interface allows you to split a transaction into logical breakpoints to control how many transactions need to be rolled back. The following figure shows how to apply SavePoint in a transaction.

  

A visual representation of SavePoint
You may not often need to use savepoint. However, in a general situation savepoint will work, that is, you need to make a series of changes, but before you know all the results are not sure which part of these changes should be retained. The following code example shows how to use the SavePoint interface.

......
Conn.setautocommit (false); 
Set a conservative transaction isolation level. 
Conn.settransactionisolation (connection.transaction_serializable); 
Statement stmt = Conn.createstatement (); 
int rows = Stmt.executeupdate ("INSERT into authors" + 
"(first_name, last_name) VALUES" + 
"(' Ghq ', ' WXL ')"); 
  //Set a named savepoint. 
SavePoint svpt = Conn.setsavepoint ("Newauthor"); 
... rows = stmt.executeupdate ("UPDATE authors set type = ' Fiction '" + 
"WHERE last_name = ' WXL '"); 
... Conn.rollback (SVPT); 
... The author has been added, but not updated. 
Conn.commit (); 
......

5. Other characteristics
  1) Meta Data API
The metadata API has been updated, and the DatabaseMetaData interface can now retrieve the SQL type hierarchy, and a new Parametermetadata interface can describe the types and attributes of the parameters in the PreparedStatement object.

  2 named parameters in Callablestatements
Before JDBC 3.0, set a parameter in a stored procedure to specify its index value, not its name. The CallableStatement interface has been updated and you can now specify the parameters by name.

  3 Changes in data types
The data types supported by JDBC have made several changes, one of which is the addition of two new data types.

To facilitate the modification of values for CLOB (Character Large object, character giant object), BLOB (Binary Large object, binary Macro object) and REF (SQL structure) type, the data type interface with the same name is updated. Next, because we are now able to update the values of these data types, the ResultSet interface has also been modified to support updates to the columns of these data types, as well as to the array type. The two new data types that are added are Java.sql.Types.DATALINK and Java.sql.Types.BOOLEAN. The new data type refers to the SQL type with the same name. DATALINK provides access to or URLs to external resources, and BOOLEAN types are logically equivalent to BIT types, but add semantic meaning. The DATALINK column value is retrieved from an instance of ResultSet by using the new GetURL () method, and the BOOLEAN type is retrieved by using Getboolean ().

Binary Large Object blob
A Blob object is a Java-language mapping of an SQL BLOB. A SQL blob is a built-in type that can store a binary large object in a database. The methods in interfaces resultset, CallableStatement, and PreparedStatement allow programmers to access SQL 99 type blobs in the same way that access SQL 92 built-in types.

In the standard implementation, the JDBC driver uses the SQL Type Locator (BLOB) in the background to implement the Blob interface. LOCATOR (BLOBs) point to the SQL BLOB values that are stored on the database server, and these actions work on the LOCATOR (locator) with the same result as the function in the BLOB value itself. This means that users can perform operations on a single BLOB instance without having to materialize the BLOB data to the user, which significantly improves performance. Because the driver uses locator (BLOB) in the background, its use is completely transparent to the programmer.

The standard behavior of a BLOB instance remains in effect until the transaction (the transaction that creates a blob) performs a commit or rollback operation.

  1. Creating a Blob Object
    The following code shows how to create a Blob object, where stmt is a statement object:
    Statement stmt = con. Createstatement (resultset.type_insensitive,
           resultset.concur_read_only);
    ResultSet rs = stmt.excutequery ("Select DATA from TABLE	1");
    If (Rs.next ()) {
      rs.first ();
      Blob Blob=rs.getblob ("DATA");
    } 
    
    A variable blob contains a logical pointer to a BLOB value that is saved in the data column in the first row of the result set Rs. Even if a variable blob does not actually contain a value in a BLOB value, the application performs operations on the BLOB as if it were on the actual data. That is, any action that an application does on a BLOB will affect the BLOB value in the table.
  2. materialized BLOB Data
    developers can invoke methods in the JDBC API on BLOB objects as if they were directly
    performing operations on the SQL blob that the object points to. However, if you want to perform operations on BLOB data, you must first materialize the BLOB data to the customer. The Blob interface provides two methods for materializing BLOB data: Getbinarystream, which materialized the BLOB data into an input stream; GetBytes, this method will make the Blob worth one part or all as a byte array. The following code shows how the blob that the blob points to is worth being materialized into an input stream:
     Java.io.InputStream in = Blob.getbinarystream ();
      BYTE B; while ((b = in.read ()) >-1) {System.out.println (b);} 
    The next code also materialized that the BLOB pointed at the blobs was worth all the data, but it produced a byte array instead of an input stream.
     Long len = Blob.length ();
      byte [] data = Blob.getbytes (1,len);
       for (int i=0;i<len;i++) {byte b = data[i];
    System.out.println (b); The 
    variable data copies all the bytes of the BLOB value that the blob points to. This is because the parameter value passed to the method GetBytes illustrates the entire BLOB value: The first parameter indicates that the byte is returned from the first byte, and the second argument indicates that the length of the byte it returns is the length of the BLOB value.
    to be explained, because of the difference between SQL and the Java language, a blob is worth the first byte at position 1, and the first element of the Java array is indexed by 0.
  3. Storing BLOB values
    To store a BLOB value in a database, the application can pass it as a parameter to the
    PreparedStatement method of Setblob. The following code implements this feature:
    PreparedStatement method of Setblob. The following code implements this function:
      Blob stats = Rs.getblob ("stats");
      PreparedStatement pstmt= con.preparedstatement (
    "UPDATE sightings SET meas=?") WHERE area = ' BEIJING ');
      Pstmt.setblob (1,stats);
      Pstmt.excuteupdate ();
    
  4. Discovering patterns in a Blob object
    If a Blob object contains a given set of bytes, the application can use the method
    Position two ways to find it. One of these methods searches for a given array of bytes, while the other searches for a given Blob object in a Blob object. If a matching result is found, the starting position of the mode byte is returned.
  5. methods to modify BLOB objects
    The new methods SetBytes and Setbinarystream in the JDBC 3.0 API allow applications to modify
    Blob objects.
    Method SetBytes has two methods to add data to a Blob object. One of these methods increases the entire contents of the given byte array, while the other method increases the specific portion of the given byte array. All two methods use a parameter description to insert the starting position of the data into the Blob object. For example, the following code snippet writes an entire byte array bytes at the first byte of a Blob object blob1. In this case, bytes contains all the bytes of the Blob object blob, so the result of the execution is that BLOB2 is written to the beginning of the BLOB1. It should be noted that if the length of the BLOB2 is 1024 bytes, then the 1024 bytes of BLOB2 will overwrite the 1024 bytes at the beginning of Blob1.
    byte [] bytes = Blob2.getbytes (1,blob2.length ());
    Blob.setbytes (1,bytes,0,512); 
    The following code snippet shows how to add only a specific part of a byte array to a BLOB object. In this case, the method SetBytes accepts two additional parameters to indicate which part of the byte array needs to be increased. One of the parameters indicates the starting offset of the byte array, and the other indicates how many contiguous bytes the byte array contains.
    byte [] bytes={...};
    Blob.setbytes (1,bytes,0,512); 
    in addition to adding bytes to a Blob object, the Blob interface provides a way to delete bytes. Method truncate takes a byte number as a parameter and shortens the Blob object based on that number.
  6. Locators and updates
    In a standard implementation, a BLOB object that points to a SQL BLOB uses the SQL locator type. A locator (locator) is a pointer to a BLOB value saved in the database, and how the DBMS updates an object that is implemented as a locator relies on the specific database. Some DBMS update BLOB values in the table, while others update only one copy of the BLOB value without changing the value in the database. In the latter case, the application must update the BLOB value directly.
    In order to discover how a DBMS updates a BLOB value, an application can invoke the DatabaseMetaData method locatorsupdatecopy. If this method returns True, the application must update the BLOB value in the database itself. The following code shows this process: first retrieving the Blob object from RS and then changing its value to the value of the byte data val. If the method locatorsupdatecopy returns True, it then executes a PreparedStatement object to update the values in the database. If the method Locatorsupdatecopy returns false, the code does nothing, because the value in the database has been updated.
    byte [] Val ={0,1,2,3,4};
      Blob Data =rs.getblob ("data");
      int numwritten = data.setbytes (1,val);
      if (dbmd.locatorupdatecopy () = = True) {
       preparedstatement pstmt= con. PreparedStatement (
    "UPDATE statistics SET DATA =? WHERE REGION = ' BEIJING ');
       Pstmt.setblob ("Data", data);
       Pstmt.executeupdate ();
    }
    

Character large Object Clob

    1. creates a Blob object
      Clob Clob = Rs.getclob (1);
      Variable CLOB can now be used to perform operations on CLOB values, assuming that the CLOB value is saved in the first column of the result set Rs.

    2. materialized CLOB data
      and materialized blobs in the same way. However, the Clob interface provides three ways to save Clob as a Java object in the customer's memory.
       
    3. Stores, Updates Clob objects
      and stores, updates blob objects similar.

Meta-Data interface use detailed
The three meta data Interface DatabaseMetaData, ResultSetMetaData, and Parametermetadata interfaces are three commonly used metadata interfaces. DatabaseMetaData provides information related to a database or DBMS; ResultSetMetaData objects provide information related to a column in a particular resultset instance The Parametermetadata object provides information about the parameters of the PreparedStatement object. The content discussed in this article is not limited to one version of JDBC, but is based on the 1.0-3.0 specification.

  • ResultSetMetaData objects
    When a SELECT statement is sent in a JDBC application, the operation returns a ResultSet object that contains the data that satisfies the condition. You can get information about the columns in this ResultSet object by creating a Resultmetadata object and by invoking the object's methods. The following code snippet creates the ResultSet object RS and then uses RS to create the ResultSetMetaData object, which contains information about the columns in Rs. ResultSetMetaData object.
       Statement stmt= con. Createstatement ();
       ResultSet rs = stmt.executequery ("SELECT * from Sales");
       ResultSetMetaData RSMD = Rs.getmetadata ();
    
    You can now use RSMD to invoke the ResultSetMetaData method to access information related to the columns in Rs. In addition to the method getColumnCount gives the total number of columns in the result set, all ResultSetMetaData methods return information about a single column and accept a parameter that represents the corresponding column number.
      1. getColumnCount Method
        This is probably the most used method in ResultSetMetaData, which returns the number of columns in the result set:
        resultset rs = stmt.exec
        Utequery ("SELECT * from Sales");
        ResultSetMetaData RSMD = Rs.getmetadata ();
        int numberofcolumns = Rsmd.getcolumncount ();
        while (Rs.next ()) {for (int i=1;i<=numberofcolumn;i++) {String s = rs.getstring (i);  System.out.println ("Column" +i + ":" +s + ");}} 
        It is worth noting that the ResultSet method used to retrieve all the column values is getstring. This is a relatively easy method when you don't know the type of each column, and if you want to be able to retrieve all the data types (including the SQL 99 data type), you can use method GetObject, which is the only way to ensure that all columns are retrieved.
      2. gets column type information
        There are two resultsetmetadata methods that can get information about the type of the result set column. This

        Two methods are Getcolumntype and Getcolumntypename. The Getcolumntype method is used to determine the JDBC type of the value stored in the specified column. The method returns the JDBC type with an int value. The following code obtains the JDBC type for the second column of Rs:
         ResultSetMetaData RSMD = Rs.getmetadata ();
        int jdbctype = Rsmd.getcolumntype (2); 
      3. Get additional information
        There are several other ways to provide information about the columns that store numeric types.
        isautoincrement iscurrency issigned getprecision getscale isnullable getcolumndisplaysize 
    1. Using the DatabaseMetaData object
      Interface DatabaseMetaData provides a number of ways to obtain database-related information. Once you have an open connection, you can create a DatabaseMetaData object that contains information about the database system.
    2. Categories of DatabaseMetaData methods
      The DatabaseMetaData method is classified according to the type of return value, which can be divided into 4 kinds.
      There are three types that return a single value, and the other returns a result set that contains data from the 1~18 column. ① method that returns a string
      The smallest category refers to the DatabaseMetaData method that returns a String object. Some of these methods can get the overall information about the DBMS, including the URL of the database, username, product name, driver information, and so on.
      ② method to return int
      ③ method of returning Boolean
      ④ method of returning ResultSet object
      These methods can return the ResultSet object, and the returned ResultSet object can contain 1 to up to 18 columns.
    3. Get information about a primary foreign key
      The main methods for returning information related to primary foreign keys are Getprimarykeys, Getimportedkeys, Getexportedkeys and Getcrossreference.
      The following code snippet shows that if a primary key is specified when the table is defined, the method Getprimarykeys can be invoked to get a description of the primary key column in the table.
       Import java.sql.*; public class static primarykeysexample{public static void Main (string args[]) {string url = ' Jdbc:mySubprotocol:myDataSo
      Urce ";
      Connection con;
               String createstring = "CREATE table SUPPLIERSPK" + "(sup_id integer NOT NULL," + "sup_name varchar (40)," +
               "Street varchar", "+" city varchar (m) "+" state char (+), "+" zip char (10), "+
      "PRIMARY KEY (SUP_ID)");
      Statement stmt; try{class.forname ("Mydriver.classname");}
       catch (Java.lang.ClassNotFoundException e) {System.err.println ("classnotfoundexception:");
      System.err.println ("E.getmessage ()");
       try{con =drivermanager.getconnection (URL, "username", "pwd");
       Stmt=con.createstatement;
       Stmt.executeupdate (createstring);
       DatabaseMetaData Dbmd=con.getmetadata ();
       ResultSet rs= Dbmd.getprimarykey (null,null, "SUPLIERSPK");
       while (Rs.next ()) {String name =rs.getstring ("table_name");
       String columnname=rs.getstring ("column_name"); String keyseq=rs.getstring ("Key_seq”);
       String pkname=rs.getstring ("Pk_name");
       SYSTEM.OUT.PRINTLN ("Table name:" +name);
       SYSTEM.OUT.PRINTLN ("Column name:" +columnname);
       SYSTEM.OUT.PRINTLN ("Sequence in key:" +keyseq);
      SYSTEM.OUT.PRINTLN ("PRIMARY Key Name:" +pkname);}
      Rs.close ();
      Stmt.close ();
      Con.close ();
       }catch (SQLException ex) {System.err.println ("SQLException:" +ex.getmessage ());}}}
      If the primary key is redundant, then method Getprimarykeys will describe each column in detail. The value in the column KEY_SEQ represents which column is described.
  • Using the Parametermetadata object

    You can use the Parametermetadata object to get information about a PreparedStatement object or a CallableStatement object. These parameters are determined by the "?" placeholder denotes, "?" Placeholders are SQL statements that are provided to the connection method Preparestatement and Preparecall. The following line of code creates a PreparedStatement object using two parameter placeholders.
    PreparedStatement pstmt=con.preparestatement ("SELECT ID from Employees where dept=?") and Salary>? ");
    These parameters are numbered according to their ordinal number, so the first parameter is numbered 1, the second parameter is number 2, and so on. In the preceding line of code, parameter 1 is a value in column dept, and Parameter 2 is a value in salary. The following code snippet is used to find out how many parameters the PreparedStatement pstmt has. First create the pstmt and use it to create the Parametermetadata object PMD, which contains information about the parameters in pstmt. Then invoke the method getColumnCount on PMD to find out how many parameters the pstmt has.

      PreparedStatement pstmt=con.preparestatement (
    "UPDATE employees set salary =? Where level=? ");
      Parametermetadata PMD = Pstmt.getparametermetadata ();
      int Count=pmd.getparametercount ();
    
    The value of the variable count should be equal to 2. Method GetParameterCount does not accept arguments because it returns information about all parameters of the PreparedStatement object. All other methods in the Parametermetadata interface accept the ordinal number to represent the parameters of the information to be queried.
  • New method Examples in JDBC 3.0API
    The JDBC 3.0 API introduces an application that determines whether the ResultSet object is still open after the commit method has been called to terminate the transaction. This function is the result set to be maintained. In resultset, two domains Hold_cursors_over_commit and Close_cursors_at_commit are added, which can be used to specify the retention of ResultSet objects. These constants can be supplied to the connection method for creating statement, PreparedStatement, and CallableStatement objects. It can also be used as a possible parameter value provided to the DatabaseMetaData method supportresultsetholdability.


    in the following code snippet, first determine whether the driver supports resultset retention and, if supported, then create a statement object that generates a ResultSet object with a retention cursor. In addition, this code specifies the type and concurrency pattern of the ResultSet object that stmt produces when it executes the query. The

    if (Boolean b =dbms.supportsresultsetholdability (ResultSet.
    Hold_cursors_over_commit) {statement.stmt=con.createstatement (resultset.type_scroll_insensitive,
    Resultset.concur_updatable, Resultset.hold_cursors_over_commit); 
    refer to the JDBC API Reference maydene Fisher etc. "

RowSet
  The rowset object is a container of tabular data that encapsulates a set of data rows obtained from the data source. In the basic implementation of the rowset interface, the data rows are fetched from the JDBC data source. Because rowsets can be customized, data in a rowset can come from spreadsheets, flat files (flat files?). or any other table style data source. The rowset object is an extension of the ResultSet interface, which means that the rowset object is scrollable, updatable, and capable of performing any action that the ResultSet object can perform.

The rowset object differs from the ResultSet object, which is the JavaBean component, so the object has a JavaBean attribute and follows its event model. Also, the properties of the rowset object allow the object to establish its own database connection and execute its own query. In addition, rowset can be disconnected, which means that in the process of using a rowset, you do not have to keep open connections to the data source. In addition, the rowset can be serialized, so it can be sent over the network to the remote object.

In general, the JDBC API can be divided into two categories: the rowset section and the driver section. Rowset and interfaces that support it are implemented using other JDBC APIs. Logically, classes that implement the rowset interface can be viewed as software that executes on the upper level of the JDBC driver.

Now in J2SE 5.0, the JDBC API can be divided into three categories, with the exception of the two categories above, and the 5 standard implementations of the rowset interface. These implementations provide a set of interfaces to extend the basic rowset interface by establishing application on these interfaces to ensure that implementation of event handling, cursor control, and other operations follows the JDBC API.

The rowset interface provides a set of basic methods that are common to all rowsets. Because all rowset objects are JavaBean components, the rowset interface has methods for adding and removing event listener, as well as for get/set all properties of rowset objects. Most properties of the rowset object support establishing a connection or executing a command. To execute SQL statements such as queries, updates, and generate a result set from which data can be obtained, a rowset uses a connection to a data source.

If a component wants to be notified of events that occur on the rowset object, it should implement the Rowsetlistener interface and register with the rowset object. This is listener, a GUI component. So each time the rowset generates an event, listener gets a notification of the event, which keeps its cursor position and data consistent with the contents of the rowset.

The rowsetinternal, Rowsetreader, and Rowsetwriter interfaces support the Reader/weiter tool for rowsets. Reader is an instance of a class that implements the Rowsetreader interface to read data and insert data into a rowset. Writer is an instance of a class that implements the Rowsetwriter interface, which is used to write the modified data back to the data source. Reader and writer, like the listener, are dynamically registered with the rowset.

The rowset object that invokes reader or writer must be an instance of the class that implements the Rowsetinternal interface. This interface provides an additional method for reader or writer to manipulate the internal state of the rowset. For example, a rowset can track its initial value, and the Rowsetinternal method allows writer to detect whether the corresponding data in the data source has been modified by another user. In addition, you can use the Rowsetinternal method to get the input parameters set for the rowset's command string, as well as to get the connection passed to the rowset. Finally, the Rowsetinternal method allows reader to set a new Rowsetmetadata object that describes the row set that Reder will insert into the rowset.

The rowset can be connected, it can also be disconnected, a connected rowset object that maintains a connection to the data source throughout the use, and an disconnected rowset that connects to its data source only when reading data from the data source or writing data back to the data source. If the rowset is disconnected, it does not require a full implementation of the JDBC driver or JDBC API. This makes it very compact and thus becomes the ideal container for sending a set of data to a thin client. This client can choose to update the data and send the rowset back to the application server. On the server side, the disconnected rowset object uses its reader to establish a connection to the data source and writes the data back to the data source. The implementation of this operation depends on how the reader is implemented. Typically, reader delegates an operation that establishes the connection and reads/writes data to the JDBC driver.

Event model for Rowset
The rowset event model enables a Java object or component to receive notification of events generated by the rowset object. The establishment of the notification mechanism includes the notified component, as well as the rowset object itself. First, every component that wishes to receive an event notification must implement the Rowsetlistener interface. The rowset object must then register each component, which is done by adding the components to the event notification component list of the rowset object. In this case, such a component is a listener, an instance of a class that implements the Rowsetlistener method, and has been registered with the rowset object.

Three kinds of events can occur in a rowset object: Cursor movement, data row changes (INS, Del, UPD), or the entire contents of the object change. The cursormoved, RowChanged, and rowsetchanged methods of the Rowsetlistener interface correspond to these events respectively. When an event occurs, the rowset creates a Rowsetevent object that uses this object to identify the rowset as an event source. The appropriate Rowsetlistender method is invoked on each listener and a Rowsetevent object is passed as an input parameter to this method, and the event is notified to all listener of the rowset.

Rowset Property
The rowset interface provides a set of JavaBeans properties that you can configure to connect to a data source and get a collection of data rows. Rowset Some properties may not be required, depending on the specific implementation. If you establish a connection with a URL or a data source name, the other property is optional as long as one of the properties is set. If two properties are set, the most recently set property is used. If the data for a rowset is obtained from a non-SQL data source that is not a supported name command, such as a spreadsheet, you do not need to set command properties.

Explanation of several interfaces

  1. Webrowset
    The Webrowset interface extends the Cacherowset interface. The ability to read and write XML-formatted rowsets is increased compared to the Cacherowset interface. The Webrowsetimpl object uses the Webrowsetxmlreader object to read the rowset in XML format and writes the data to an XML-formatted rowset using the Webrowsetxmlwriter object.   The XML version contains the metadata of the Webrowsetsetimpl object, as well as its own data. The Webrowsetimpl object and the Cachedrowsetimpl similarity are both connecting thin clients to the application server. So they are all suitable for thin customers to provide data, different places are used by the two protocols. The former uses the Http/xml protocol to communicate with the middle tier, and the latter uses RMI/IIOP.
  2. Joinrowset
    The Joinrowset object allows programmers to combine data from two different rowset objects. This merging of data is useful when data is stored in different data sources associated with p/f keys or other columns that are uniquely corresponding. Any rowset implementation can participate in merging, but typically, the two sides of the connection are two Cachedrowsetimpl objects. By merging related data into a Joinrowsetimpl object, the application can handle any other type of rowset object to process the data.
    Suppose there are two tables: the Employees table and the Bonus_plan table, the first data column of the two tables is the ID, the data column is the primary key, and the information for the two tables is now matched to merge:
     Joinrowsetimpl jrs=new Joinrowsetimpl ();
      ResultSet rs1 = Stmt.executequery ("SELECT * FROM Employees");
      Cachedrowsetimpl empl=new Cachedrowsetimpl ();
      Empl.populate (RS1);
      Empl.setmatchcolumn (1);
      Jrs.addrowset (EMPL);
      ResultSet rs2=stmt.executequery ("SELECT * from Bonum_plan");
      Cachedrowsetimpl bonums= new Cachedrowsetimpl ();
      Bonus.populate (RS2);
      Bonus.setmatchcolumn (1); Jrs.addrowset (bonus);//merged 

    Xaconnection Introduction
    The Xaconnection object is a Pooledconnection object that can be used for distributed transactions. It represents a physical connection to a database that can be used by a server in a multi-tier structure to create a connection object that is returned to the application. Because it is obtained by extending the Pooledconnection interface, it inherits all of its methods and adds its own method Getxaresource.
    Commands in distributed transactions can be sent to multiple DBMS servers distributed transactions are managed with a middle-tier application server and external transaction managers and JDBC servers, and these three parts of the middle tier infrastructure provide plumbing.
    The first element of a distributed transaction infrastructure is the transaction manager, which can be a JTA implementation. The transaction manager controls the transaction boundary and the two-phase commit process. It initiates and closes the components associated with the Distributed transaction Xaconnection object and tracks the DBMS servers that are involved in the distributed transaction. The transaction manager runs in each DBMS to decide whether to commit the transaction, and the transaction manager submits the transaction only if all the DBMS agrees to commit, otherwise it is rollback.
    Another element of a distributed transaction is the JDBC driver that supports the JDBC API, and the driver must contain classes that implement the Xadatasource and Xaconnection interfaces. The Xadataresource interface is similar to the DataSource interface, but it creates objects that are xaconnection objects rather than connection objects. The Xaconnection object that inherits from Pooledconnection is special in that it can be used to get Xasource objects. The transaction manager uses this Xarource object to start and end the component associated with this xaconnection in a distributed transaction.
    The third part of the distributed transaction infrastructure is usually a connection pooling module. The Xaconnection interface inherits from the Pooledconnection interface, which means that the database connection in a distributed transaction can come from a connection pool managed by a connection pool module.

    -->
    Td>dev2dev id:lhbing, Dev2dev forum Moderator, WEBLOIGC and Java technology enthusiast

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.