将数组传递给 oracle 过程

发布于 2024-10-20 09:08:46 字数 66 浏览 2 评论 0原文

我想将两个数组从java发送到oracle存储过程。 第一个数组是字符串数组,第二个数组是字符数组 我该怎么做这个?

I want to send two arrays form java to oracle stored procedures.
The first Array is array of strings and the second is array of chars
how can I make this??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

温柔女人霸气范 2024-10-27 09:08:46

下面是如何执行此操作的示例。

以下脚本在数据库中设置一个表、一个类型和一个存储过程。该过程采用数组类型的参数并将数组的每一行插入到表中:

CREATE TABLE strings (s VARCHAR(4000));

CREATE TYPE t_varchar2_array AS TABLE OF VARCHAR2(4000);
/

CREATE OR REPLACE PROCEDURE p_array_test(
    p_strings      t_varchar2_array
)
AS
BEGIN
  FOR i IN 1..p_strings.COUNT
  LOOP
    INSERT INTO strings (s) VALUES (p_strings(i));
  END LOOP;
END;
/

然后,Java 代码演示将数组传递到此存储过程中:

import java.sql.*;
import oracle.jdbc.*;
import oracle.sql.*;

public class ArrayTest {
    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver(new OracleDriver());
        Connection conn = DriverManager.getConnection(
            "jdbc:oracle:thin:@localhost:1521:xe", "user", "pass");

        CallableStatement stmt = conn.prepareCall("BEGIN p_array_test(?); END;");

        // The first parameter here should be the name of the array type.
        // It's been capitalised here since I created it without using
        // double quotes.
        ArrayDescriptor arrDesc =
            ArrayDescriptor.createDescriptor("T_VARCHAR2_ARRAY", conn);

        String[] data = { "one", "two", "three" };
        Array array = new ARRAY(arrDesc, conn, data);
        stmt.setArray(1, array);
        stmt.execute();

        conn.commit();
        conn.close();
    }
}

如果运行 SQL 脚本,然后运行 ​​Java 类,然后查询表string,您应该发现所有数据都已插入到表中。

当您说“字符数组”时,我猜您指的是 Java char 数组。如果我猜对了,那么我认为您最好将 char 转换为 String ,然后使用与上面相同的方法。

Here's an example of how to do it.

The following script sets up a table, a type and a stored procedure in the database. The procedure takes a parameter of the array type and inserts each row of the array into the table:

CREATE TABLE strings (s VARCHAR(4000));

CREATE TYPE t_varchar2_array AS TABLE OF VARCHAR2(4000);
/

CREATE OR REPLACE PROCEDURE p_array_test(
    p_strings      t_varchar2_array
)
AS
BEGIN
  FOR i IN 1..p_strings.COUNT
  LOOP
    INSERT INTO strings (s) VALUES (p_strings(i));
  END LOOP;
END;
/

The Java code then demonstrates passing an array into this stored procedure:

import java.sql.*;
import oracle.jdbc.*;
import oracle.sql.*;

public class ArrayTest {
    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver(new OracleDriver());
        Connection conn = DriverManager.getConnection(
            "jdbc:oracle:thin:@localhost:1521:xe", "user", "pass");

        CallableStatement stmt = conn.prepareCall("BEGIN p_array_test(?); END;");

        // The first parameter here should be the name of the array type.
        // It's been capitalised here since I created it without using
        // double quotes.
        ArrayDescriptor arrDesc =
            ArrayDescriptor.createDescriptor("T_VARCHAR2_ARRAY", conn);

        String[] data = { "one", "two", "three" };
        Array array = new ARRAY(arrDesc, conn, data);
        stmt.setArray(1, array);
        stmt.execute();

        conn.commit();
        conn.close();
    }
}

If you run the SQL script and then the Java class, and then query the table strings, you should find that all of the data has been inserted into the table.

When you say 'an array of chars', I'm guessing that you mean an array of Java chars. If I've guessed right, then I think you'd be best off converting the chars to Strings and then using the same approach as above.

榕城若虚 2024-10-27 09:08:46

看这里:
http://download.oracle.com/docs /cd/B19306_01/java.102/b14355/oraarr.htm#i1058512

这是我的简短示例:

1)在数据库上

SQL> create or replace type string_array as table of varchar2(100);
  2  /

Type created.

SQL> create or replace function to_string(p_array in string_array) return varchar2
  2  as
  3     l_string varchar2(32767);
  4     i binary_integer;
  5  begin
  6     i := p_array.first();
  7     while i is not null loop
  8        l_string := l_string || p_array(i) || ';';
  9        i := p_array.next(i);
 10     end loop;
 11     l_string := rtrim(l_string, ';');
 12     return l_string;
 13  end;
 14  /

Function created.

2)在java中

public class ArrayTest {
    public static void main(String[] args) throws SQLException {
        DriverManager.registerDriver(new OracleDriver());
        OracleConnection connection = (OracleConnection) DriverManager.getConnection(...);

        String[] elements = {"abc", "def", "geh"};
        ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("STRING_ARRAY", connection);
        ARRAY array = new ARRAY(descriptor, connection, elements);

        OracleCallableStatement stmt = (OracleCallableStatement) connection.prepareCall("{? = call to_string(?)}");
        stmt.registerOutParameter(1, Types.VARCHAR);
        stmt.setARRAY(2, array);
        stmt.execute();

        String result = stmt.getString(1);
        System.out.println("to_string returned: " + result);
    }
}

似乎有效:输出说

to_string returned: abc;def;geh

Look here:
http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/oraarr.htm#i1058512

and here is my short example:

1) on database

SQL> create or replace type string_array as table of varchar2(100);
  2  /

Type created.

SQL> create or replace function to_string(p_array in string_array) return varchar2
  2  as
  3     l_string varchar2(32767);
  4     i binary_integer;
  5  begin
  6     i := p_array.first();
  7     while i is not null loop
  8        l_string := l_string || p_array(i) || ';';
  9        i := p_array.next(i);
 10     end loop;
 11     l_string := rtrim(l_string, ';');
 12     return l_string;
 13  end;
 14  /

Function created.

2) in java

public class ArrayTest {
    public static void main(String[] args) throws SQLException {
        DriverManager.registerDriver(new OracleDriver());
        OracleConnection connection = (OracleConnection) DriverManager.getConnection(...);

        String[] elements = {"abc", "def", "geh"};
        ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("STRING_ARRAY", connection);
        ARRAY array = new ARRAY(descriptor, connection, elements);

        OracleCallableStatement stmt = (OracleCallableStatement) connection.prepareCall("{? = call to_string(?)}");
        stmt.registerOutParameter(1, Types.VARCHAR);
        stmt.setARRAY(2, array);
        stmt.execute();

        String result = stmt.getString(1);
        System.out.println("to_string returned: " + result);
    }
}

seems to work: output says

to_string returned: abc;def;geh
好菇凉咱不稀罕他 2024-10-27 09:08:46

由于 ArrayDescriptor 自 12c 起已被弃用,因此不应再使用它。
这是在 12c 中对我有用的代码片段:

            Array array = ((OracleConnection) connection).createOracleArray("T_VARCHAR2_ARRAY", data);
            CallableStatement statement = connection.prepareCall("{call p_array_test(?)}");
            statement.setArray(1, array);
            statement.execute();

Since ArrayDescriptor is deprecated since 12c, it should not be used anymore.
Here's a code sniplet that worked for me in 12c:

            Array array = ((OracleConnection) connection).createOracleArray("T_VARCHAR2_ARRAY", data);
            CallableStatement statement = connection.prepareCall("{call p_array_test(?)}");
            statement.setArray(1, array);
            statement.execute();
删除→记忆 2024-10-27 09:08:46

正则表达式解决

select * from table_a  a where a.col in (select   regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) from dual
connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;)

Regex solve

select * from table_a  a where a.col in (select   regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) from dual
connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;)
烟酒忠诚 2024-10-27 09:08:46

PeudoCode 的实现方式与我相同。

    # 1.You will require a structDescriptor object for an object equivalent in pl sql like :

    StructDescriptor structDes= new StructDescriptor("<schemaname in caps>.<sql_object_name>", connectionObject);

    # 2. You will need to pass one object values such name, class, id to an object array in order and accordance to 'sql_object_name' object. 

    For exmaple:
    STRUCT[] structArray=new STRUCT[<ListObj>.size()];
    int index=0;
    for (a in ListObj){

    Object[] object=new Object[]{a.getName(),a.getId()};
    STRUCT struct=new STRUCT(structDes ,connectionObject,object);
               structArray[index]=struct;
               index++;

    }

    ArrayDescriptor arrayDes=ArrayDescriptor.createDescriptor(
        "<Schema name>.<table object from sql>", connectionObject);

    ARRAY array=new ARRAY(arrayDes,connectionObject, structArray);

   then pass it to proc 

   .declareParameters(
   new SqlInOutParameter("<parameter to proc name>",OracleTypes.ARRAY,"
   <schema name>.<sql_array_or_table_obj>"))

   like 
   Hashmap<String, Object> map= new HashMap<>();
   map.put("<parameter to proc name>",array);
   psStatement.execute(map);

希望有帮助。此顺序可能会根据要求和使用的 SQL 数据库类型而有所不同,但基础是相同的。

我从我的其他答案之一复制了这个答案。

使用简单的 jdbc 调用将数组作为输入参数传递给 Oracle 存储过程

PeudoCode for the same how I achieved.

    # 1.You will require a structDescriptor object for an object equivalent in pl sql like :

    StructDescriptor structDes= new StructDescriptor("<schemaname in caps>.<sql_object_name>", connectionObject);

    # 2. You will need to pass one object values such name, class, id to an object array in order and accordance to 'sql_object_name' object. 

    For exmaple:
    STRUCT[] structArray=new STRUCT[<ListObj>.size()];
    int index=0;
    for (a in ListObj){

    Object[] object=new Object[]{a.getName(),a.getId()};
    STRUCT struct=new STRUCT(structDes ,connectionObject,object);
               structArray[index]=struct;
               index++;

    }

    ArrayDescriptor arrayDes=ArrayDescriptor.createDescriptor(
        "<Schema name>.<table object from sql>", connectionObject);

    ARRAY array=new ARRAY(arrayDes,connectionObject, structArray);

   then pass it to proc 

   .declareParameters(
   new SqlInOutParameter("<parameter to proc name>",OracleTypes.ARRAY,"
   <schema name>.<sql_array_or_table_obj>"))

   like 
   Hashmap<String, Object> map= new HashMap<>();
   map.put("<parameter to proc name>",array);
   psStatement.execute(map);

Hope it helps. This sequence may vary as per requirement and type of sql database used, but base is same.

I have copied this answer from one of my other answers.

Pass array as input parameter to an oracle stored procedure using simple jdbc call

债姬 2024-10-27 09:08:46

新方法是解开 OracleConnection 的包装,然后使用 createOracleArray

OracleConnection oracleConnection = getJdbcTemplate().getDataSource().getConnection().unwrap(OracleConnection.class);
Array array = oracleConnection.createOracleArray("REF_TYPE_ARRAY", referralTypeId);

inputParameters.put("itemIds", array); 

另请参阅:如何创建 oracle.sql.ARRAY对象?

The new approach is to unwrap the OracleConnection and then use createOracleArray.

OracleConnection oracleConnection = getJdbcTemplate().getDataSource().getConnection().unwrap(OracleConnection.class);
Array array = oracleConnection.createOracleArray("REF_TYPE_ARRAY", referralTypeId);

inputParameters.put("itemIds", array); 

Also see: How to create an oracle.sql.ARRAY object?

唱一曲作罢 2024-10-27 09:08:46

您可以使用 Oracle 类型将 Java 对象映射到 Oracle。此外,还有 Spring JDBC 实用程序。

You can use Oracle Types to map Java objects to Oracle. Also, there's Spring JDBC utilities.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文