Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2341708
  • 博文数量: 2110
  • 博客积分: 18861
  • 博客等级: 上将
  • 技术积分: 24420
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-05 18:23
文章分类

全部博文(2110)

文章存档

2011年(139)

2010年(1971)

我的朋友

分类: Oracle

2010-02-23 22:33:40

 本文给出了读写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下即可。

阅读(1260) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~