Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Thursday 25 July 2013

Returning data from anonymous PL/SQL block

The example here demonstrates the use of an anonymous PL/SQL block to return data to a calling Java program. It also shows how to use nested tables in PL/SQL, and the use of auto-generated column values. This requires Java 5 and Oracle 10g Release 2. In order to use the example, on the database
  1. Create a trigger on the database table that inserts a value into the new row, or use the following piece of code before the insert statement and insert the seqval variable in the id column.
    select req_seq.nextval into seqval from dual;
    Here req_seq is a sequence holding the req_id sequence.
  2. Create two new types as shown below
    create or replace TYPE RQ_ROW AS TABLE OF VARCHAR(500);
    create or replace TYPE RQ_LIST AS TABLE OF RQ_ROW;
    create or replace TYPE RESULTS_LIST AS TABLE OF RESULT_LIST;
    create or replace TYPE RESULT_LIST AS VARRAY OF NUMBER;

    RQ_ROW represents a row in the table. RQ_LIST represents a set of rows. RESULT_LIST is a two element list where the first element represents the index and the second element is the autogenerated column value. This was used since nested tables do not guarantee the order of elements. RESULTS_LIST is used to return the autogenerated keys back to Java.
Once the database is setup use the following PL/SQL block to insert rows into the table

DECLARE
rqResults RESULTS_LIST;
rqRow RQ_ROW;
rqList RQ_LIST;
p Number;
q Number;

BEGIN

rqList := ?;
rqresults := results_list();
q := rqList.COUNT;
FOR k IN 1..q LOOP
INSERT INTO rquisitions(RQ_CD, RQ_STATUS)
VALUES (rqList(k)(1), rqList(k)(2)) RETURNING rq_id INTO p;
rqResults.EXTEND;
rqResults(k) := RESULT_LIST(k,p);
END LOOP;

? := rqResults;

END;
rqList is the input parameter here. Note the ? := rqResults; This represents the output parameter. The following code snippet shows the implementation of this in a Java program.

private String sql = "DECLARE " +
"rqResults RESULTS_LIST; " +
"rqRow RQ_ROW; " +
"rqList RQ_LIST; " +
"p Number; " +
"q Number;" +
"BEGIN " +
"rqList := ?; " +
"rqresults := results_list(); " +
"q := rqList.COUNT; " +
"FOR k IN 1..q LOOP " +
"INSERT INTO rquisitions(RQ_CD, RQ_STATUS) VALUES " +
"(rqList(k)(1), rqList(k)(2)) RETURNING rq_id INTO p; " +
"rqResults.EXTEND; " +
"rqResults(k) := RESULT_LIST(k,p);" +
"END LOOP; " +
"? := rqResults;" +
"END;";


public void load() {
Connection connection = getConnection();
String RQ_COLS[] = { "req_id" };
try {
String data[][] = {{"ab", "cd"}, {"ef", "gh"}, {"ij", "kl"}};

ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor("SCOTT.RQ_LIST", connection);
Array array = new ARRAY(descriptor, connection, data);
CallableStatement cstmt = null;


cstmt = connection.prepareCall(sql);
cstmt.setArray(1, array);

cstmt.registerOutParameter(2, Types.ARRAY, "SCOTT.RESULTS_LIST");

cstmt.executeUpdate();

// Print the result set.

Array arr = cstmt.getArray(2);

ResultSet rSet = arr.getResultSet();
long[] values = new long [6];
while (rSet.next()) {

Array arr1 = (Array)rSet.getArray(2);
ResultSet rrSet = arr1.getResultSet();

while(rrSet.next()) {

int index = rrSet.getInt(2);
if(rrSet.next()) {
long value = rrSet.getLong(2);
values[index] = value;
}
}
}

for(int i = 1; i < values.length; i ++) {
System.out.println(i + ", " + values[i]);
}


cstmt.close();
connection.close();

} catch (SQLException e) {
e.printStackTrace();
}

Note the use of a callable statement and that the out parameter is an array. It is actually an array of arrays. The java.sql.Array class provides a getResultSet() method that can be used to browse the array elements.

This code was tested on Java 5.0 with Oracle 10g Release 2.

References:

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...