关闭

racle的STRUCT和VARRAY的读写方法

842人阅读 评论(0) 收藏 举报
 

Oracle的STRUCT和VARRAY的读写方法

巧巧电脑网络 2010-02-25 qqread 佚名   收藏此文 
本文给出了读写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); 然后。
 

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

相关文章:Oracle初学者必知的100个问题

oracle安装完成后的初始口令? UPDATE AAA SET BNS_SNM=(SELECT BNS_SNM FROM BBB WHERE AAA.DPT_NO=BBB.DPT_NO) W HERE BBB.DPT_NO IS NOT NULL; 23. P4电脑安装方法 将SYMCJIT.DLL改为SYSMCJIT.OLD 24. 何查询SERVER是不是OPS? SELECT * FROM V$OPTION。

 

===============

 

Use Oracle's VARRAY Through JDBC
This code snippet demonstrates how to use Oracle's VARRAY through JDBC. The code:
  1. Creates VARRAYs of different lengths.
  2. Contains a table to store data of above array type.
  3. Stores the objects in an array.Inserts them into database table in two different ways (with SQL and ArrayDescriptor).</LI itxtHarvested="0" itxtNodeId="459">

import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.oracore.Util;
import oracle.jdbc.*;
public class VArrayManipulation
{
public static void main (String args[])
throws Exception
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
// The sample retrieves an varray of type "STRING_VARRAY",
// materializes the object as an object of type ARRAY.
// A new ARRAY is then inserted into the database.
String url = "<connection url>";
// Connect to the database
Connection conn =
DriverManager.getConnection (url, "<user>" , "<password>");
conn.setAutoCommit (false);
// Create a Statement
Statement stmt = conn.createStatement ();
try
{
stmt.execute ("DROP TABLE sample_varray_table");
stmt.execute ("DROP TYPE string_varray");
}
catch (SQLException e)
{
//Exceptions will be thrown if Table and types doesnt exist . Ignore this
}
stmt.execute ("CREATE TYPE string_varray AS VARRAY(10) OF VARCHAR2(100)");
stmt.execute ("CREATE TABLE sample_varray_table (acol string_varray)");
//Insert using SQL
stmt.execute ("INSERT INTO sample_varray_table VALUES (string_varray('Test1', 'Test2'))");
ResultSet rs = stmt.executeQuery("SELECT acol FROM sample_varray_table");
printResultSet (rs);
//Insert using ArrayDescriptor
// create a new ARRAY object
String arrayElements[] = { "Test3", "Test4" };
ArrayDescriptor desc = ArrayDescriptor.createDescriptor
("STRING_VARRAY", conn);
ARRAY newArray = new ARRAY(desc, conn, arrayElements);
PreparedStatement ps =
conn.prepareStatement ("insert into sample_varray_table values (?)");
((OraclePreparedStatement)ps).setARRAY (1, newArray);
ps.execute ();
rs = stmt.executeQuery("SELECT acol FROM sample_varray_table");
printResultSet (rs);
// Close all the resources
rs.close();
ps.close();
stmt.close();
conn.close();
}
public static void printResultSet (ResultSet rs)
throws SQLException
{
System.out.println("********Fetch Starts....********");
int line = 0;
while (rs.next())
{
line++;
System.out.println("********Row "+line+" : ");
ARRAY array = ((OracleResultSet)rs).getARRAY (1);
System.out.println ("Array is of type "+array.getSQLTypeName());
System.out.println ("Array is of length "+array.length());
// get Array elements
String[] values = (String[]) array.getArray();
for (int i=0; i<values.length; i++)
{
System.out.println("index "+i+" = "+values[i] );
}
}
System.out.println("********Fetch Ends....********");
}
}

http://www.devx.com/tips/Tip/22034

 

 

 

 

 

 

 

===============

上一篇: 如何在Oracle中修改Collection类型的变量。 | 下一篇: Javascript获取字符串字节数的方法
 如何在JAVA程序中使用Struct一次传入多条数据给Oracle的存储过程。     
为了减少连接Oracle数据库的数量,需要将多条数据作为变量一次传入Oracle的存储过程中。方法如下:
步骤一:定义对象类型。 
CREATE TYPE department_type AS OBJECT (
DNO NUMBER (10),
NAME VARCHAR2 (50),
LOCATION VARCHAR2 (50)
);
步骤二:定义一个对象类型的数组对象。
CREATE TYPE dept_array AS TABLE OF department_type;
步骤三:定义存储过程来插入数据。
CREATE OR REPLACE PACKAGE objecttype AS
  PROCEDURE insert_object (d dept_array);
END objecttype;
CREATE OR REPLACE PACKAGE BODY objecttype
AS
PROCEDURE insert_object (d dept_array)
AS
BEGIN
FOR i IN d.FIRST..d.LAST
LOOP
INSERT INTO department_teststruct
VALUES (d(i).dno,d(i).name,d(i).location);
END LOOP;
END insert_object; 
END objecttype;

步骤四(可选步骤,即可以不做):定义一个Java class来映射对象中类型。
步骤五:定义Java方法来调用存储过程。 

import java.sql.Connection; 
import java.sql.DriverManager;
import oracle.jdbc.OracleCallableStatement;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;

public class TestStruct ...{
    public static void main(String[] args)
    ...{
            sendStruct();
    }
    public static void sendStruct() 
    ...{
        Connection dbConn = null;
        try...{    
            Object[] so1 = ...{"10","Accounts","LHR"}; 
            Object[] so2 = ...{"20","HR","ISB"}; 
            OracleCallableStatement callStatement = null; 
            Class.forName("oracle.jdbc.driver.OracleDriver");
            dbConn = DriverManager.getConnection("jdbc:oracle:thin:@ServerName:Port:ORa", "UserName", "Password");
            StructDescriptor st = new StructDescriptor("DEPARTMENT_TYPE",dbConn);
            STRUCT s1 = new STRUCT(st,dbConn,so1);
            STRUCT s2 = new STRUCT(st,dbConn,so2);
            STRUCT[] deptArray = ...{s1,s2};
            ArrayDescriptor arrayDept = ArrayDescriptor.createDescriptor("DEPT_ARRAY", dbConn);
            ARRAY deptArrayObject = new ARRAY(arrayDept, dbConn, deptArray); 
            callStatement = (OracleCallableStatement)dbConn.prepareCall("{call insert_object(?)}");
            ((OracleCallableStatement)callStatement).setArray(1, deptArrayObject);
            callStatement.executeUpdate(); 
            dbConn.commit();
            callStatement.close(); 
        } 
        catch(Exception e)...{ 
            System.out.println(e.toString());
        }
    }
}
http://zhidao.baidu.com/question/49553096.html

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2420840次
    • 积分:32179
    • 等级:
    • 排名:第157名
    • 原创:962篇
    • 转载:826篇
    • 译文:6篇
    • 评论:42条
    文章分类
    最新评论
    我的栏目
    我的栏目测试