Oracle的STRUCT和VARRAY的读写方法


本文给出了读写Oracle的特殊数据类型STRUCT和VARRAY的操作方法。

  首先,创建类型

  CREATE TYPE Struct_Test AS OBJECT(s VARCHAR(30), i NUMBER);

  CREATE TYPE number_varray AS VARRAY(10) OF NUMBER(12, 2);

  然后,创建表

  CREATE TABLE test(i NUMBER, obj Struct_Test);

  REATE TABLE VARRAY_TABLE(col_number_array number_varray)

  然后,插入数据

  //插入STRUCT数据

  Object[] values = new Object[]{”str”, new BigDecimal(123)};

  oracle.sql.StructDescriptor structDesc = oracle.sql.StructDescriptor.createDescriptor(”Struct_Test”, cn);

  oracle.sql.STRUCT oracleStruct = new oracle.sql.STRUCT(structDesc, cn, values);

  // Create a prepared statement for insertion into test

  PreparedStatement ps = connection.prepareStatement(”INSERT INTO test VALUES(?,?)”);

  // Set the values to insert

  ps.setInt(1, 123);

  ps.setObject(2, oracleStruct);

  // Insert the new row

  ps.execute();

  //插入VARRAY数据

  // 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, cn, arrayValues);

  // Create a prepared statement for insertion into varray_table

  PreparedStatement ps = cn.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();

  最后,读取数据

  //读取STRUCT数据

  ResultSet resultSet = stmt.executeQuery(”SELECT * FROM test”);

  while (resultSet.next()) {

  // Get the Struct_Test value from the second column obj

  oracle.sql.STRUCT oracleStruct = (oracle.sql.STRUCT)resultSet.getObject(2);

  // Get the object1 values from each row

  Object[] values = oracleStruct.getAttributes();

  // Get the first value of object1, which is a string

  String str = (String)values[0];

  BigDecimal i = (BigDecimal)values[1];

  }

  //读取VARRAY数据

  // Create a statement

  Statement stmt = cn.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();

  }

  注意:乱码问题,依赖于nls_charset12.jar,否则字符串类型的数据是乱码,插入失败,读取出来是null

  请将nls_charset12.jar放于classpath下即可。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3