7 Oracle Driver : Data Types

Data Types
Table 7-2 lists the data types supported by the Oracle driver and describes how they are mapped to the JDBC data types.
Table 7-2. Oracle Data Types 
VARCHAR or TIMESTAMP

1
Supported only for Oracle 10g and higher.

2
When JDBCBehavior=0, the data type depends on the JVM used by the application. For JVMs earlier than Java SE 6, the first value applies. For Java SE 6 and higher, the second value applies.

3
Supported only for Oracle9i and higher.

4
When FetchTSWTSasTimestamp=false (default), this data type is mapped to the JDBC VARCHAR data type; when FetchTSWTSasTimestamp=true, it is mapped to the JDBC TIMESTAMP data type.

For More Information:
■
See “Using Date/Time Data Types” for more information about the TIMESTAMP, TIMESTAMP WITH LOCAL TIME ZONE, and TIMESTAMP WITH TIME ZONE data types.
■
See “Using Collection Data Types” for more information about the VARRAY, TABLE, and OBJECT data types.
■
See “Returning and Inserting/Updating XML Data” for more information about the XMLType data type.
■
Refer to Chapter 4 “getTypeInfo()” in the DataDirect Connect Series for JDBC Reference for a description of the data types returned by the getTypeInfo() method.
Using Date/Time Data Types
Oracle9i and higher supports the following date/time data types:
■
■
■
Date/Time Session Parameters
Table 7-3 describes the session parameters the Oracle driver sets at connection time that affect how the driver supports date/time data types.
The Oracle session time zone. The Oracle driver sets the time zone to the current time zone as reported by the JVM.
The default timestamp with time zone format. The Oracle driver uses the JDBC timestamp escape format with the time zone field appended:
TIMESTAMP Data Type
The Oracle TIMESTAMP data type is mapped to the JDBC TIMESTAMP data type.
TIMESTAMP WITH LOCAL TIME ZONE Data Type
The Oracle TIMESTAMP WITH LOCAL TIME ZONE data type is mapped to the JDBC TIMESTAMP data type.
When retrieving TIMESTAMP WITH LOCAL TIME ZONE columns, the value returned to the user is converted to the time zone specified by the TIME_ZONE session parameter.
When setting TIMESTAMP WITH LOCAL TIME ZONE columns:
■
Using a timestamp (using PreparedStatement.setTimestamp, for example), the value set is converted to the time zone specified by the TIME_ZONE session parameter.
■
Using a string (using PreparedStatement.setString(), for example), the string is passed as-is to the server. The supplied string must be in the format specified by the NLS_TIMESTAMP_TZ_FORMAT session parameter. If not, the Oracle server generates an error when it attempts to convert the string to the TIMESTAMP WITH LOCAL TIME ZONE type.
TIMESTAMP WITH TIME ZONE Data Type
By default, the Oracle TIMESTAMP WITH TIME ZONE data type is mapped to the JDBC VARCHAR data type.
When retrieving TIMESTAMP WITH TIME ZONE values as a string (using resultSet.getString(), for example), the value is returned as the string representation of the timestamp including time zone information. The string representation is formatted as:
'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM'
where:
■
YYYY is the 4-digit year.
■
MM is the month.
■
DD is the day.
■
HH24 is the hour in 24-hour format.
■
MI is the minutes.
■
SS is the seconds.
■
FF is the fractional seconds.
■
TZH is the time zone hours and TZM is the time zone minutes. The time zone is represented as the difference in hours and minutes between the time zone and GMT.
By default, retrieving TIMESTAMP WITH TIME ZONE values as a timestamp (using resultSet.getTimeStamp, for example) is not supported because the time zone information stored in the database would be lost when the data is converted to a timestamp. To provide backward compatibility with existing applications, you can use the FetchTSWTZasTimestamp property to allow TIMESTAMP WITH TIME ZONE values to be returned as a timestamp. The default value of the FetchTSWTSasTimestamp property is false, which disables retrieving TIMESTAMP WITH TIME ZONE values as timestamps.
When setting TIMESTAMP WITH TIME ZONE columns:
■
Using a timestamp (using PreparedStatement.setTimestamp(), for example), the value set is converted to the time zone specified by the TIME_ZONE session parameter.
■
Using a string (using PreparedStatement.setString(), for example), the string is passed as-is to the server. The supplied string must be in the format specified by the NLS_TIMESTAMP_TZ_FORMAT session parameter. If not, the Oracle server generates an error when it attempts to convert the string to the TIMESTAMP WITH TIME ZONE type.
Using Collection Data Types
Oracle8i and higher supports the following collection data types:
■
■
■
The examples in this section are based on the following Create Table and data type definitions:
CREATE TYPE num_varray AS VARRAY(4) OF NUMBER(12,2)
CREATE TYPE num_table AS TABLE of NUMBER(12,2)
CREATE TYPE city_object as OBJECT (
Name VARCHAR2(40),
Province VARCHAR2(40),
City_Code VARCHAR2(10),
Population Number)
 
CREATE TABLE complex_type_table (array_col num_varray, table_col num_table, object_col city_object) NESTED TABLE TABLE_COL STORE AS TABLE_COL_NT
VARRAY/TABLE
The Oracle VARRAY and TABLE data types map to the JDBC ARRAY data type. To use these data types as a parameter, an array must be created using the createArray() method of the ExtConnection interface. See “ExtConnection Interface” for more information about this method.
NOTES:
■
■
The Oracle driver does not support using the VARRAY and TABLE data types with Oracle index-by tables, also known as associative arrays.
If you want more accurate metadata information for either of these data types, set the CatalogOptions connection property to 8, but be aware that this can negatively affect performance. See the description of CatalogOptions in “Connection Properties” for details.
Example A: Selecting Data From an Array
This example selects two columns, reads them into separate arrays, and retrieves the objects from the arrays.
Statement st = connection.createStatement();
 
ResultSet resultSet = st.executeQuery(
"SELECT array_col, table_col FROM complex_type_table");
// Loop through the result set and retrieve the objects
while(resultSet.next()) {
// Use getArray to read the value into an array
java.sql.Array myVarray = resultSet.getArray(1);
java.sql.Array myTable = resultSet.getArray(2);
// Call getArray() method to retrieve the array of objects
Object varrayValues[] = (Object[])myVarray.getArray();
Object tableValues[] = (Object[])myTable.getArray();
}
Example B: Inserting Data into an Array
This example constructs two separate arrays and inserts the array objects into their respective columns.
Object objArray[] = new Object[4];
objArray[0] = new java.math.BigDecimal (1);
objArray[1] = new java.math.BigDecimal (2);
objArray[2] = new java.math.BigDecimal (3);
objArray[3] = new java.math.BigDecimal (4);
// Construct the array for the VARRAY
java.sql.Array colVarray = ((com.ddtek.jdbc.extensions.ExtConnection)connection).createArray(
"NUM_VARRAY", objArray);
 
// Construct the array for the Table
java.sql.Array colTable = ((com.ddtek.jdbc.extensions.ExtConnection)connection).createArray(
"NUM_TABLE", objArray);
PreparedStatement ps = connection.prepareStatement(
"INSERT INTO complex_type_table (array_col, table_col) VALUES (?, ?)");
// Bind the array objects to be inserted
ps.setArray(1, colVarray);
ps.setArray(2, colTable);
ps.executeUpdate();
ps.close();
OBJECT
The Oracle OBJECT data type maps to the JDBC STRUCT data type. To use this data type as a parameter, the parameter value must be created using the createStruct() method of the Connection interface. See “Connection” for more information about this method.
NOTE: The OBJECT data type is not supported for bulk load operations.
If you require more accurate metadata information for this data type, set the CatalogOptions connection property to 8. See the description of CatalogOptions in “Connection Properties” for details.
Example A: Selecting Data From an Object
Statement st = connection.createStatement();
 
ResultSet resultSet = st.executeQuery(
"SELECT object_col FROM complex_type_table");
// Loop through the result set and retrieve the objects
while(resultSet.next()) {
// Get the row into java.sql.STRUCT
java.sql.Struct mystruct =
(java.sql.Struct)(resultSet.getObject(1));
// Get the individual field values for the object
Object cols[] = mystruct.getAttributes();
}
Example B: Inserting Data into an Object
Object objArray[] = new Object[4];
String name = "Morrisville";
String state = "North Carolina";
String code = "27560";
java.math.BigDecimal densityint = new java.math.BigDecimal (4);
objArray[0] = name;
objArray[1] = state;
objArray[2] = code;
objArray[3] = densityint;
// Construct the Struct
java.sql.Struct colStruct = connection.createStruct(
"CITY_OBJECT", objArray);
PreparedStatement ps = connection.prepareStatement(
"INSERT INTO complex_type_table (object_col) VALUES (?)");
// Bind the STRUCT representing the object to be inserted
ps.setObject(1, colStruct, java.sql.Types.STRUCT);
ps.executeUpdate();
ps.close();
Returning and Inserting/Updating XML Data
For Oracle9i and higher, the Oracle driver supports the Oracle XMLType data type. Which JDBC data type the XMLType data type is mapped to depends on whether the JDBCBehavior property is set. If JDBCBehavior=0, XML data is mapped to SQLXML or CLOB, depending on which JVM your application is using. The driver maps the XMLType data type to the JDBC SQLXML data type if your application is using Java SE 6 or higher. If your application is using an earlier JVM, the driver maps the XMLType data type to the JDBC CLOB data type.
Returning XML Data
The driver can return XML data as character data. For example, given a database table defined as:
CREATE TABLE xmlTable (id int, xmlCol XMLType NOT NULL)
the driver can return the XML data as character data using the following code:
String sql="SELECT xmlCol FROM xmlTable";
ResultSet rs=stmt.executeQuery(sql)
String charXML=rs.getString(1)
The result set column is described with a column type of CLOB and the column type name is xmlType.
Your application can use the following methods to return data stored in XML columns as character data:
■
■
■
■
■
The driver converts the XML data returned from the database server from the character set encoding used by the database server to the UTF-16 Java String encoding.
Your application can use the following method to return data stored in XML columns as ASCII data:
ResultSet.getAsciiStream()
The driver converts the XML data returned from the database server from the character set encoding used by the database server to the ISO-8859-1 (latin1) encoding.
NOTE: The conversion caused by using the getAsciiStream() method may create XML that is not well-formed because the content encoding is not the default encoding and does not contain an XML declaration specifying the content encoding. Do not use the getAsciiStream() method if your application requires well-formed XML.
Inserting/Updating XML Data
When inserting to or updating XMLType columns, the data to be inserted or updated must be the XMLType data type. Oracle provides the xmltype() function to construct an XMLType data object. The xmlData argument of the xmltype() function can be specified as a string literal or a parameter marker. If specified as a parameter marker, the parameter value can be set using the following methods:
■
■
■
■
The driver converts the character representation of the data to the XML character set used by the database server and sends the converted XML data to the server. The driver does not parse or remove any XML processing instructions.
The following code inserts data into an XMLType column using a statement with a string literal as the xmlData argument of the xmltype() function:
// Insert xml data as a literal
String sql = "INSERT INTO XMLTable VALUES (1, xmltype('" +
   "<emp><empNo>123</empNo><empName>Mark</empName></emp>'))";
 
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
The following code inserts data into an XMLType column using a prepared statement:
// Insert xml data as a String parameter
String xmlStr = "<emp><empNo>234</empNo><empName>Trish</empName></emp>";
String sql = "INSERT INTO XMLTable VALUES (?, xmltype(?))";
 
PreparedStatement prepStmt = con.prepareStatement(sql);
prepStmt.setInt(1, 2);
prepStmt.setString(2, xmlStr);
prepStmt.executeUpdate();
REF CURSOR Data Type
REF CURSOR is the Oracle data type for a cursor variable. Because JDBC does not support a cursor variable data type, the Oracle driver returns REF CURSOR output parameters and return values to the application as result sets. The Oracle driver converts the REF CURSOR data to a result set that can be returned using getResultSet() or getMoreResults(). Because REF CURSOR data is returned as result sets and not as output parameters, REF CURSOR output parameters are not included in results from DatabaseMetaData.getProcedureColumns() calls.
In your application, omit any parameter markers for the REF CURSOR as shown in the following examples and do not declare an output parameter for the REF CURSOR. These examples reference the following stored procedure definition:
CREATE PACKAGE foo_pkg AS
   TYPE EmpCurTyp IS REF CURSOR RETURN fooTbl%ROWTYPE;
   PROCEDURE selectEmployeeManager(empId IN INT, empCursor OUT EmpCurTyp,
   mgrCursor out EmpCurTyp);
   FUNCTION selectEmployee2 (empId IN INT) return EmpCurTyp;
END foo_pkg;
Example A: Calling a Stored Procedure That Returns a Single REF CURSOR
// Call a function that accepts an input parameter and returns a
// REF CURSOR as the return value.
// Omit the placeholder for the refcursor return value parameter.
// The REF CURSOR is returned as a result set.
sql = "{call foo_pkg.selectEmployee2(?)}";
 
callStmt = con.prepareCall(sql);
callStmt.setInt(1, 2);
moreResults = callStmt.execute();
 
while (true) {
 
   if (moreResults) {
   
      // Get the result set that represents the REF CURSOR
      resultSet = callStmt.getResultSet();
      displayResults(resultSet);
      
      resultSet.close();
      resultSet = null;
      
      System.out.println();
   }
   else {
      
         updateCnt = callStmt.getUpdateCount();
         if (updateCnt == -1) {
            break;
         }
         System.out.println("Update Count: " + updateCnt);
    }
    moreResults = callStmt.getMoreResults();
}
Example B: Calling a Stored Procedure that Returns Multiple REF CURSORs
// Call the stored procedure that accepts an input parameter and
// returns two REF CURSORs.
// Omit the placeholder for REF CURSOR parameters.
// The REF CURSORs are returned as result sets.
sql = "{call foo_pkg.selectEmployeeManager(?)}";
 
callStmt = con.prepareCall(sql);
callStmt.setInt(1, 2);
moreResults = callStmt.execute();
 
while (true) {
 
   if (moreResults) {
   
      // Get the result set that represents the REF CURSOR
      resultSet = callStmt.getResultSet();
      displayResults(resultSet);
      resultSet.close();
   }
   else {
      
         updateCnt = callStmt.getUpdateCount();
         if (updateCnt == -1) {
            break;
         }
      }
      
      moreResults = callStmt.getMoreResults();
}