Thứ Tư, 24 tháng 10, 2012

VARRAY in Oracle and Java

Inserting a VARRAY Value into an Oracle Table Using a Prepared Statement:
try {
    // Create an oracle.sql.ARRAY object to hold the values
    oracle.sql.ArrayDescriptor arrayDesc =
        oracle.sql.ArrayDescriptor.createDescriptor("number_varray", connection);
    int arrayValues[] = {123, 234};
    oracle.sql.ARRAY array = new oracle.sql.ARRAY(arrayDesc, connection, arrayValues);

    // Create a prepared statement for insertion into varray_table
    PreparedStatement ps =
        connection.prepareStatement("INSERT INTO varray_table VALUES(?)");

    // Set the values to insert
    ((oracle.jdbc.driver.OraclePreparedStatement)ps).setARRAY(1, array);

    // Insert the new row
    ps.execute();
} catch (SQLException e) {
}
 
Creating a VARRAY Type in an Oracle Database
try {
    Statement stmt = connection.createStatement();

    // Create a 10-element VARRAY of NUMBERs
    stmt.execute("CREATE TYPE number_varray AS VARRAY(10) OF NUMBER(12, 2)");

    // Create a table with a column to hold the new VARRAY type
    stmt.execute("CREATE TABLE VARRAY_TABLE(col_number_array number_varray)");
} catch (SQLException e) {
}
 
Getting a VARRAY Value from an Oracle Table
try {
    // Create a statement
    Statement stmt = connection.createStatement();

    // Select rows from varray_table
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM varray_table");

    // Get the VARRAY values from each row
    while (resultSet.next()) {
        // Get the VARRAY value in the first column
        oracle.sql.ARRAY array = ((oracle.jdbc.driver.OracleResultSet)resultSet).getARRAY(1);

        // Get the VARRAY elements; values.length is the number of values in the VARRAY
        java.math.BigDecimal[] values = (java.math.BigDecimal[])array.getArray();
    }
} catch (SQLException e) {
}
 
Inserting a VARRAY Value into an Oracle Table
try {
    // Create a statement
    Statement stmt = connection.createStatement();

    // Insert a row with an array of two values
    stmt.execute ("INSERT INTO varray_table VALUES(number_varray(123, 234))");
} catch (SQLException e) {
} 


Source: http://www.exampledepot.com/

Không có nhận xét nào:

Đăng nhận xét