PL SQL Array Output
Hi,
I have below pl sql type structure.
create or replace
TYPE xx_emp_obj AS OBJECT (
empno NUMBER,
ename VARCHAR2 (200),
last_name VARCHAR2 (200),
job VARCHAR2 (200),
mgr_id NUMBER,
deptno NUMBER,
CONSTRUCTOR FUNCTION xx_emp_obj
RETURN SELF AS RESULT
create or replace
TYPE xx_emp_tbl IS TABLE OF xx_emp_obj;Wrote below package to hold values.
create or replace PACKAGE xx_emp_ret_pkg as
PROCEDURE get_emp_prc(p_deptno IN NUMBER, x_emp_tbl OUT xx_emp_tbl);
END xx_emp_ret_pkg;
create or replace PACKAGE BODY xx_emp_ret_pkg as
PROCEDURE print(p_msg VARCHAR2) IS
BEGIN
dbms_output.put_line(p_msg);
END;
PROCEDURE get_emp_prc(p_deptno IN NUMBER, x_emp_tbl OUT xx_emp_tbl) IS
CURSOR cur_get_emp_det(pc_deptno NUMBER) IS
SELECT empno,ename,job,mgr,deptno FROM scott.emp where deptno = pc_deptno;
l_emps_tbl xx_emp_tbl := xx_emp_tbl();
l_emp_obj xx_emp_obj;
v_empno NUMBER;
i NUMBER;
BEGIN
i:=0;
FOR r_get_emp_det IN cur_get_emp_det(10) LOOP
l_emp_obj.empno := r_get_emp_det.empno;
l_emp_obj.ename := r_get_emp_det.ename;
l_emps_tbl.EXTEND;
i := i+1;
l_emps_tbl(i) := l_emp_obj;
END LOOP;
x_emp_tbl := l_emps_tbl;
END get_emp_prc;
END xx_emp_ret_pkg;Please let me know after passing parameters to packaged procedure how to capture outbound table type parameter and print it to check values ?
Thanks ,
Kiran
Edited by: 911681 on Jan 5, 2013 12:38 AM
Welcome to the forum!
Whenever you post provide your 4 digit Oracle version (result of SELECT * FROM V$VERSION)
>
Please let me know after passing parameters to packaged procedure how to capture outbound table type parameter and print it to check values ?
>
The method I prefer is to use a PIPELINED function rather than expensive PGA memory and having to pass collections around. Then you can just query the function as if it were a table; no special handling or loop required at all.
I'm surprised that Solomon didn't mention this and refer you to his classic reply in this thread
Re: Pipe line function
If you define what you need in a package spec you can use PL/SQL types (e.g. %ROWTYPE) and Oracle will create the actual SQL types for you automagically!
create or replace
package pkg1
as
type emp_table_type is table of emp%rowtype;
function get_emp(p_deptno number)
return emp_table_type pipelined;
end;
create or replace
package body pkg1
as
function get_emp(p_deptno number)
return emp_table_type pipelined is
begin
for v_rec in (select * from emp where deptno = p_deptno) loop
pipe row(v_rec);
end loop;
end;
end;
SQL> select * from table(pk1.get_emp(20))
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 smith CLERK 7902 12/17/1980 800 20
7566 jones MANAGER 7839 4/2/1981 2975 20
7788 scott ANALYST 7566 4/19/1987 3000 20
7876 adams CLERK 7788 5/23/1987 1100 20
7902 ford ANALYST 7566 12/3/1981 3000 20If you don't have a table with the columns you need just define a CURSOR in the package spec and base your %ROWTYPE on that
create or replace
package pkg2
as
CURSOR emp_cur is (SELECT empno, ename, job, mgr, deptno FROM emp);
type pkg_emp_table_type is table of emp_cur%rowtype;
function get_emp(p_deptno number)
return pkg_emp_table_type
pipelined;
end;
create or replace
package body pkg2
as
function get_emp(p_deptno number)
return pkg_emp_table_type pipelined is
begin
for v_emp_rec in (SELECT empno, ename, job, mgr, deptno
FROM emp where deptno = p_deptno) loop
pipe row(v_emp_rec);
end loop;
end;
end;
/ In both of the above cases the TYPEs are automatically created by Oracle. In 10g they are visible if you query USER_TYPES. But , as Solomon said in his reply:
>
in 11g they are not visible in DBA_TYPES and require select from data dictionary tables sys.type$ and sys.attribute$.
>
If you want to manually create you own types and manually load data into them you can but that is the hard way.
-- type to match emp record
create or replace type emp_scalar_type as object
(EMPNO NUMBER(4) ,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7, 2),
COMM NUMBER(7, 2),
DEPTNO NUMBER(2)
-- table of emp records
create or replace type emp_table_type as table of emp_scalar_type
-- pipelined function
create or replace function get_emp( p_deptno in number )
return emp_table_type
PIPELINED
as
TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
emp_cv EmpCurTyp;
l_rec emp%rowtype;
begin
open emp_cv for select * from emp where deptno = p_deptno;
loop
fetch emp_cv into l_rec;
exit when (emp_cv%notfound);
pipe row( emp_scalar_type( l_rec.empno, LOWER(l_rec.ename),
l_rec.job, l_rec.mgr, l_rec.hiredate, l_rec.sal, l_rec.comm, l_rec.deptno ) );
end loop;
return;
end;
select * from table(get_emp(20))
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 smith CLERK 7902 12/17/1980 800 20
7566 jones MANAGER 7839 4/2/1981 2975 20
7788 scott ANALYST 7566 4/19/1987 3000 20
7876 adams CLERK 7788 5/23/1987 1100 20
7902 ford ANALYST 7566 12/3/1981 3000 20
Similar Messages
-
Bind PL/SQL array to PHP array
Hi all!
I try to bind a PL/SQL array (nested tables, index by integer) returned by a PL/SQL-function to an PHP array.
Here is the code:
create or replace package MyPackage as
TYPE my_type IS TABLE OF VARCHAR2(1024);
FUNCTION MyFunction RETURN my_type;
end MyPackage;
create or replace PACKAGE BODY MyPackage is
FUNCTION MyFunction RETURN my_type IS
t_docs my_type;
begin
t_docs := my_type('val0','val1','val2');
return t_docs;
end MyFunction;
end MyPackage;
In the PHP-code ist looks like this
$query = "begin :vals := MyPackage.MyFunction; end;";
$stmt = oci_parse ($conn, $query);
oci_bind_array_by_name($stmt, ":vals", $vals_array, 5, 512, SQLT_CHR);
oci_execute ($stmt);
Output:
PLS-00382: expression is of wrong type. Error in Line....
This error point to
begin :vals := MyPackage.MyFunction; end;
^^^
Questions:
Is it generally possible to bind a pl/sql array to a php array? Or only the other was around?
Could you please post a snipet of code how to do it the right way :-)
Thanks a lot for your help! ChristianAs you noted, you can't return a PL/SQL array and map it to a PHP array when it is a record type. Likewise, you can't map an object type to a PHP array. You can return a reference cursor through PL/SQL, and then fetch the function result with oci_fetch_assoc($rc).
Alternatively, you can return an object type collection or a pipelined table function result into PHP. It's a bit long but you'll find examples on my blog. Start here, and there's a link to a full discussion of pipelined table functions:
http://blog.mclaughlinsoftware.com/2009/03/19/beats-a-reference-cursor/
This is an object table example, which you may prefer over pipelined table functions:
http://blog.mclaughlinsoftware.com/2009/03/23/object-record-collections/
Hope this helps. -
How do I get an array output on a Formula Node?
My problem is simply that I cannot figure out how to get an output on a Formula Node to be an array. Documentation states that "you must declare local arrays and output arrays in the Formula Node" but doesn't say anything more than than. Attempts to put something like "float32 out[100];" for an array output called "out" fail.
If anybody knows how you can do this or even knows if it is possible I would appriciate your help.
Thanks,
NaveenI found a typo in the formula node I was doing that was making the output not be an array. I don't think I was getting the error before but I was going to put together an example VI to attach here and I found it. So, thanks for your help even tho it was a stupid little mistake on my part.
-
The ABAP/4 Open SQL array insert results in duplicate database records
Hi,
Iam getting following error :
The ABAP/4 Open SQL array insert results in duplicate database records.
Error in ABAP application program.
The current ABAP program "SAPLV60U" had to be terminated because one of the
statements could not be executed.
This is probably due to an error in the ABAP program.
" Information on where terminated
The termination occurred in the ABAP program "SAPLV60U" in "VBUK_BEARBEITEN".
The main program was "SAPMSSY4 ".
The termination occurred in line 503 of the source code of the (Include)
program "LV60UF0V"
of the source code of program "LV60UF0V" (when calling the editor 5030).
Processing was terminated because the exception "CX_SY_OPEN_SQL_DB" occurred in
the
procedure "VBUK_BEARBEITEN" "(FORM)" but was not handled locally, not declared
in the
RAISING clause of the procedure.
The procedure is in the program "SAPLV60U ". Its source code starts in line 469
of the (Include) program "LV60UF0V "."
Please assist how to proceed further ..
Many thanks
Mujeeb.Sorry, THe correct note is 402221.
Description from the note
<< Please do not post SAP notes - they are copyrighed material >>
Edited by: Rob Burbank on Feb 22, 2009 3:46 PM -
ABAP/4 Open SQL array insert results in duplicate databaserecordsfor pk13
Hi Experts, when I am working with pk13n tranaction iam getting an error message stating that update was terminated by user. when i am checking with st22 it gives the following message. please give the solution , iam sending the code as well.
An exception occurred that is explained in detail below.
The exception, which is assigned to class 'CX_SY_OPEN_SQL_DB', was not caught
in
procedure "SAVE_DATA" "(FORM)", nor was it propagated by a RAISING clause.
Since the caller of the procedure could not have anticipated that the
exception would occur, the current program is terminated.
The reason for the exception is:
If you use an ABAP/4 Open SQL array insert to insert a record in
the database and that record already exists with the same key,
this results in a termination.
(With an ABAP/4 Open SQL single record insert in the same error
situation, processing does not terminate, but SY-SUBRC is set to 4.) please find the below code please give the solution for this error message.
1 *eject
2 *----
3 * Verbuchen der Daten *
4 *----
5 FORM SAVE_DATA.
6
7 DATA: lf_menge LIKE ekpo-menge VALUE 0, "717464
8 lf_netwr LIKE ekpo-netwr VALUE 0.
9
10 * Einteilungen löschen --> Array Delete aus Tabelle DEKET
11 DESCRIBE TABLE DEKET LINES SY-TFILL.
12 IF SY-TFILL GT 0.
13 DELETE EKET FROM TABLE DEKET.
14 IF SY-SUBRC NE 0.
15 MESSAGE A865.
16 ENDIF.
17 EKET_DELETE = EKET_DELETE + SY-DBCNT.
18 REFRESH: DEKET.
19 CLEAR : DEKET.
20 ENDIF.
21
22 * Einteilungen hinzufügen --> Array Insert aus Tabelle IEKET
23 DESCRIBE TABLE IEKET LINES SY-TFILL.
24 IF SY-TFILL GT 0.
>> INSERT EKET FROM TABLE IEKET.
26 IF SY-SUBRC NE 0.
27 MESSAGE A864.
28 ENDIF.
29 EKET_INSERT = EKET_INSERT + SY-DBCNT.
30 REFRESH: IEKET.
31 CLEAR : IEKET.
32 ENDIF.
33
34 * Check whether the qty in EKPO-MENGE is correct: note 717464
35 SELECT SUM( menge ) FROM eket INTO lf_menge
36 WHERE ebeln = ekpo-ebeln
37 AND ebelp = ekpo-ebelp.
38 IF sy-subrc = 0 AND ekpo-menge <> lf_menge.
39 IF ekpo-ktmng <> 0.
40 refe1 = ekpo-zwert * lf_menge / ekpo-ktmng.
41 ELSE.
42 refe1 = ekpo-zwert * lf_menge / 1000.
43 ENDIF.
44 IF refe1 > maxwert.Hi,
Well I don't know why you have duplicates, this is a functionnal issue. But you get the dump due the the message number 864 that triggers the abend... Changing the message type to 'E', 'S' or 'I' will prevent the dump but I guess this message has a good reason to be
Kr,
Manu. -
Problem Encountering in oracle.sql.ARRAY type
Hi,
i am using one stored procedure to get a set of records.
i am getting it by mapping those things with java.sql.Array. And after that i am getting the values as ResultSet from that Array. The same thing is working fine in Windows platform. If i posted those thing into Unix - AIX, i am facing an ArrayIndexOutofBoundsException while getting ResultSet from oracle.sql.ARRAY class. I checked out ARRAY instance.it is not null. Both Application and Database are same except O.S.
Can Anybody help me. I need it imm.
Thanks in Advance
Regards
Eswaramoorthy.GHi
Did you ever figure out what the problem was with this? We have a client that is experiencing the same problem on AIX but we cannot reproduce using their database running under NT nor Sun. Any information would be appreciated. You can respond directly to [email protected]
Thanks in adavance
Rick DeMilia
Sungard DataSystems -
The ABAP/4 Open SQL array insert results in duplicate Record in database
Hi All,
I am trying to transfer 4 plants from R/3 to APO. The IM contains only these 4 plants. However a queue gets generated in APO saying 'The ABAP/4 Open SQL array insert results in duplicate record in database'. I checked for table /SAPAPO/LOC, /SAPAPO/LOCMAP & /SAPAPO/LOCT for duplicate entry but the entry is not found.
Can anybody guide me how to resolve this issue?
Thanks in advance
Sandeep PatilHi Sandeep,
Now try to delete ur location before activating the IM again.
Use the program /SAPAPO/DELETE_LOCATIONS to delete locations.
Note :
1. Set the deletion flag (in /SAPAPO/LOC : Location -> Deletion Flag)
2. Remove all the dependencies (like transportation lane, Model ........ )
Check now and let me know.
Regards,
Siva.
null -
Conversion of java Array to oracle SQL Array while calling Stored Procedure
How java Array can be converted to oracle SQL array while calling Stored procedure with callable statement.
i.e java Array ---> Sql Array in Oracle while setting the datatypes to callable statement arguments.Look at:
http://forum.java.sun.com/thread.jsp?forum=48&thread=376735&tstart=0&trange=15
Paul -
New to Graphics, trying to display array output in a single window
I am trying to figure out how to use the GUI components of JAVA.
What I am trying to do is take my packaged array output and list it in a single window. All that ever prints is last array data set. The last keeps overwritting the previous. How do I keep the previous data shown while listing the next in the array?
Below are my three classes. The Frame Class is the class containing the display method. It is called near the bottom of the Product Class.
Product.java
// Inventory Program Part 4
/* This program will store multiple entries
for office supplies, give the inventory value,
sort the data by Product Name,
and output the results using a GUI */
import javax.swing.text.JTextComponent;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JOptionPane; //Uses class JOptionPane
import java.util.Scanner; //Uses class Scanner
import java.util.Arrays; //Uses class Arrays
public class Product
private String productBrand[]; // Declares the array
public void setProductBrand( String brand[] ) // Declare setProductBrand method
productBrand = brand; // stores the productbrand
} // End setProductBrand method
public String getProductBrand( int counter ) // Declares getProductBrand method
return productBrand[ counter ]; // Returns data using counter to define the element
} // End method getProductBrand
public double restockingFee( double value ) // Declares restocking Fee method
double fee = 0; // Declares variable fee
fee = value * 0.05; // Calculates the sum of values
return fee; // Returns the restocking fee
} // End method restockingFee
public String inventoryValue( double value[] , int number, String name[] ) // Declares inventoryValue method
OfficeSupplies myOfficeSupplies = new OfficeSupplies(); //Creates OfficeSupplies Object
Product myProduct = new Product();
double total = 0; // Declares variable total
for ( int counter = 0; counter < number ; counter++ )
total += ( value[ counter ] + myProduct.restockingFee( value[ counter ] ) ); // Calculates the sum of values
return String.format( "%s$%.2f", "Total Inventory Value: " , total ); // Returns the total value
} // End method inventoryValue
// main method begins execution
public static void main( String args[] )
Scanner input = new Scanner( System.in ); //Creates Scanner object to input from command window
Product myProduct = new Product(); //Creates Product object
OfficeSupplies myOfficeSupplies = new OfficeSupplies(); //Creates OfficeSupplies Object
//Prompt for maxNumber using JOptionPane
String stringMaxNumber =
JOptionPane.showInputDialog( "Enter the number of products you wish to enter" );
int maxNumber = Integer.parseInt( stringMaxNumber );
String prodName[] = new String[ maxNumber ]; // Declares prodName array
int numberUnits[] = new int[ maxNumber ]; // Declares maxNumber array
float unitPrice[] = new float[ maxNumber ]; // Declares unitPrice array
double value[] = new double[ maxNumber ]; // Declares value array
String brand[] = new String [ maxNumber ]; // Declares brand array
String stringNumberUnits[] = new String [ maxNumber]; // Declares array
String stringUnitPrice[] = new String [ maxNumber ]; // Declares array
int productNumber[] = new int[ maxNumber ]; // Declares array
for ( int counter = 0; counter < maxNumber; counter++ ) // For loop for the number of products to enter
productNumber[ counter ] = counter;
myOfficeSupplies.setProductNumber( productNumber ); // Sends the Product name to method setProductNumber
//Prompt for product name using JOptionPane
prodName[ counter ] =
JOptionPane.showInputDialog( "Enter the Product Name" );
myOfficeSupplies.setProductName( prodName ); // Sends the Product name to method setProductName
//Prompt for brand name using JOptionPane
brand[ counter ] =
JOptionPane.showInputDialog( "Enter the Brand name of the Product" );
myProduct.setProductBrand( brand ); // Sends the Brand name to method setProductBrand
//Prompt for number of units using JOptionPane
stringNumberUnits[ counter ] =
JOptionPane.showInputDialog( "Enter the Number of Units" );
numberUnits[ counter ] = Integer.parseInt( stringNumberUnits[ counter ] );
myOfficeSupplies.setNumberUnits( numberUnits ); // Sends the Number Units to the method setNumberUnits
//Prompt for unit price using JOptionPane
stringUnitPrice[ counter ] =
JOptionPane.showInputDialog( "Enter the Unit Price" );
unitPrice[ counter ] = Float.parseFloat( stringUnitPrice[ counter ]);
myOfficeSupplies.setUnitPrice( unitPrice ); // Sends the Unit Price to the method setUnitPrice
value[ counter ] = numberUnits[ counter ] * unitPrice[ counter ]; // Calculates value for each item
myOfficeSupplies.setProductValue( value ); // Sends the product value to the method setProductValue
Arrays.sort( prodName, String.CASE_INSENSITIVE_ORDER ); // Calls method sort from Class Arrays
Frame myFrame = new Frame();
myFrame.displayData( myProduct, myOfficeSupplies, maxNumber );
// Outputs Total Inventory Value using a message dialog box
JOptionPane.showMessageDialog( null, myProduct.inventoryValue( value, maxNumber, prodName ),
"Total Inventory Value", JOptionPane.PLAIN_MESSAGE );
} // End method main
} // end class ProductOfficeSupplies.java ----> This is the data container
// Inventory Program Part 4
/* Stores the array values */
public class OfficeSupplies // Declaration for class Payroll
private int productNumber[];
public void setProductNumber( int number[] ) // Declare setProductNumber method
productNumber = number; // stores the product number
} // End setProductNumber method
public int getProductNumber( int counter ) // Declares getProductNumber method
return productNumber[ counter ];
} // End method getProductNumber
private String productName[];
public void setProductName( String name[] ) // Declare setProductName method
productName = name; // stores the Product name
} // End setProductName method
public String getProductName( int counter ) // Declares getProductName method
return productName[ counter ];
} // End method getProductName
private int numberUnits[];
public void setNumberUnits( int units[] ) // Declare setNumberUnits method
numberUnits = units; // stores the number of units
} // End setNumberUnits method
public int getNumberUnits( int counter ) // Declares getNumberUnits method
return numberUnits[ counter ];
} // End method getNumberUnits
private float unitPrice[];
public void setUnitPrice( float price[] ) // Declare setUnitPrice method
unitPrice = price; // stores the unit price
} // End setUnitPrice method
public float getUnitPrice( int counter ) // Declares getUnitPrice method
return unitPrice [ counter ];
} // End method getUnitPrice
private double productValue[];
public void setProductValue( double value[] ) // Declare setProductValue method
productValue = value; // stores the product value
} // End setProductValue method
public double getProductValue( int counter ) // Declares getProductValue method
return productValue[ counter ];
} // End method getProductValue
} // end class OfficeSuppliesFrame.java ------> Contains the display method
import java.awt.Color;
import javax.swing.text.JTextComponent;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JOptionPane; //Uses class JOptionPane
public class Frame extends JFrame
public Frame() //Method declaration
super( "Products" );
} // end frame constructor
public void displayData( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
//Here I attempted to use an array to output all of the array data in a single window
// JTextArea myTextArea[] = new JTextArea[ maxNumber ]; // Declares myTextArea array to display output
JTextArea myTextArea = new JTextArea(); // textarea to display output
// For loop to display data array in a single Window
for ( int counter = 0; counter < maxNumber; counter++ ) // Loop for displaying each product
// myTextArea[ counter ].setText( packageData( myProduct, myOfficeSupplies, counter ) + "\n" );
// add( myTextArea[ counter ] ); // add textarea to JFrame
myTextArea.setText( packageData( myProduct, myOfficeSupplies, counter ) + "\n" );
add( myTextArea ); // add textarea to JFrame
} // End For Loop
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize( 450, maxNumber*400 ); // set frame size
setVisible( true ); // display frame
public String packageData( Product myProduct, OfficeSupplies myOfficeSupplies, int counter ) // Method for formatting output
return String.format( "%s: %d\n%s: %s\n%s: %s\n%s: %s\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f",
"Product Number", myOfficeSupplies.getProductNumber( counter ),
"Product Name", myOfficeSupplies.getProductName( counter ),
"Product Brand",myProduct.getProductBrand( counter ),
"Number of Units in stock", myOfficeSupplies.getNumberUnits( counter ),
"Price per Unit", myOfficeSupplies.getUnitPrice( counter ),
"Total Value of Item in Stock is", myOfficeSupplies.getProductValue( counter ),
"Restock charge this product is", myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ),
"Total Value of Inventory plus restocking fee", myOfficeSupplies.getProductValue( counter )+
myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ) );
} // end method packageData
}Lets pretend that your assignment was to manage a list of employees of a store, and that each employee is identified by their name, position, and hourly wage. If you created a program along the lines of your current product program, I picture you creating three separate ArrayLists (or arrays), one for each variable, something like this:
import java.util.ArrayList;
public class MyEmployees1
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<String> positions = new ArrayList<String>();
private ArrayList<Double> hourlyWages = new ArrayList<Double>();
public void add(String name, String position, double wage)
names.add(name);
positions.add( position);
hourlyWages.add(wage);
public void removed()
// TODO: I am nervous about trying to manage this!
//.......... more
}This program tries to manage three separate parallel arrays (arraylists actually). They are parallel because the 3rd item in the names list corresponds to the 3rd item in the positions list and also the hourlywages list. If I wanted to delete data, I'd have to be very careful to delete the correct item in all three lists. If I tried to sort one list, I'd have to sort the other two in exactly the same way. It is extremely easy to mess this sort of program up.
Now lets look at a different approach. Say we created a MyEmployee class that contains the employee's name, position, and wage, along with the appropriate constructors, getters, setters, toString method, etc... something like so:
import java.text.NumberFormat;
public class MyEmployee
private String name;
private String position;
private double hourlyWage;
public MyEmployee(String name, String position, double hourlyWage)
this.name = name;
this.position = position;
this.hourlyWage = hourlyWage;
public String getName()
return name;
public String getPosition()
return position;
public double getHourlyWage()
return hourlyWage;
public String toString()
// don't worry about these methods here. They're just to make the output look nice
NumberFormat currency = NumberFormat.getCurrencyInstance();
return String.format("Name: %-15s Position: %-15s Wage: %s",
name, position, currency.format(hourlyWage));
}Now I can create a MyEmployees2 class that holds a single list of MyEmployee objects, like so:
import java.util.ArrayList;
public class MyEmployees2
private ArrayList<MyEmployee> employeeList = new ArrayList<MyEmployee>();
public boolean add(MyEmployee employee)
return employeeList.add(employee);
public boolean remove(MyEmployee employee)
return employeeList.remove(employee);
public void display()
for (MyEmployee employee : employeeList)
System.out.println(employee);
public static void main(String[] args)
MyEmployees2 empl2 = new MyEmployees2();
empl2.add(new MyEmployee("John Smith", "Salesman", 20));
empl2.add(new MyEmployee("Jane Smyth", "Salesman", 25));
empl2.add(new MyEmployee("Fred Flinstone", "Janitor", 15));
empl2.add(new MyEmployee("Barney Rubble", "Supervisor", 35));
empl2.add(new MyEmployee("Mr. Spacely", "The Big Boss", 45));
empl2.display();
}Now if I want to add an Employee, I only add to one list. Same if I want to remove, only one list, and of course, the same for sorting. It is much safer and easier to do things this way. Make sense? -
Save SQL select output as html page on another box.
How can I save a simple sql select output on another server as a html page?
Hi,
You can use the Oracle product WebDB (Oracle Portal) to create reports in HTML over the DB (simplest way).
Instead You can use SQL*Plus on the remote server (where You want to spool), enable the spool to file (using SPOOL) and create the select as
SELECT 'html tags' | | field/s | | 'html tags'
FROM your_table;Using this solution You have to manually "draw" the report.
Hope this helps.
Bye Max
null -
Deadlock in Oracle.sql.ARRAY type
Hi,
We've come across the deadlock situation below when running multiple J2EE MDB instances that are trying to write to the DB:
[deadlocked thread] [ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)':
Thread '[ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)'' is waiting to acquire lock 'oracle.jdbc.driver.T4CConnection@90106ee' that is held by thread '[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)''
Stack trace:
oracle.sql.ARRAY.toBytes(ARRAY.java:673)
oracle.jdbc.driver.OraclePreparedStatement.setArrayCritical(OraclePreparedStatement.java:5985)
oracle.jdbc.driver.OraclePreparedStatement.setARRAYInternal(OraclePreparedStatement.java:5944)
oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8782)
oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8278)
oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:8868)
oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:240)
weblogic.jdbc.wrapper.PreparedStatement.setObject(PreparedStatement.java:287)
org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:356)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:127)
org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.setValues(PreparedStatementCreatorFactory.java:298)
org.springframework.jdbc.object.BatchSqlUpdate$1.setValues(BatchSqlUpdate.java:192)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614)
org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883)
org.springframework.jdbc.object.BatchSqlUpdate.flush(BatchSqlUpdate.java:184)
com.csfb.fao.rds.rfi.common.dao.storedprocs.SaveEarlyExceptionBatchStoredProc.execute(SaveEarlyExceptionBatchStoredProc.java:93)
com.csfb.fao.rds.rfi.common.dao.EarlyExceptionDAOImpl.saveEarlyExceptionBatch(EarlyExceptionDAOImpl.java:34)
com.csfb.fao.rds.rfi.application.rulesengine.RulesEngine.saveEarlyExceptions(RulesEngine.java:302)
com.csfb.fao.rds.rfi.application.rulesengine.RulesEngine.executeRules(RulesEngine.java:209)
com.csfb.fao.rds.rfi.application.rulesengine.RulesEngine.onMessage(RulesEngine.java:97)
com.csfb.fao.rds.feeds.process.BaseWorkerMDB.onMessage(BaseWorkerMDB.java:518)
weblogic.ejb.container.internal.MDListener.execute(MDListener.java:466)
weblogic.ejb.container.internal.MDListener.transactionalOnMessage(MDListener.java:371)
weblogic.ejb.container.internal.MDListener.onMessage(MDListener.java:327)
weblogic.jms.client.JMSSession.onMessage(JMSSession.java:4547)
weblogic.jms.client.JMSSession.execute(JMSSession.java:4233)
weblogic.jms.client.JMSSession.executeMessage(JMSSession.java:3709)
weblogic.jms.client.JMSSession.access$000(JMSSession.java:114)
weblogic.jms.client.JMSSession$UseForRunnable.run(JMSSession.java:5058)
weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516)
weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
[deadlocked thread] [ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)':
Thread '[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'' is waiting to acquire lock 'oracle.jdbc.driver.T4CConnection@b48b568' that is held by thread '[ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)''
Stack trace:
oracle.sql.ARRAY.toBytes(ARRAY.java:673)
oracle.jdbc.driver.OraclePreparedStatement.setArrayCritical(OraclePreparedStatement.java:5985)
oracle.jdbc.driver.OraclePreparedStatement.setARRAYInternal(OraclePreparedStatement.java:5944)
oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8782)
oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8278)
oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:8868)
oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:240)
weblogic.jdbc.wrapper.PreparedStatement.setObject(PreparedStatement.java:287)
org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:356)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:127)
org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.setValues(PreparedStatementCreatorFactory.java:298)
org.springframework.jdbc.object.BatchSqlUpdate$1.setValues(BatchSqlUpdate.java:192)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614)
org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883)
org.springframework.jdbc.object.BatchSqlUpdate.flush(BatchSqlUpdate.java:184)
com.csfb.fao.rds.rfi.common.dao.storedprocs.SaveEarlyExceptionBatchStoredProc.execute(SaveEarlyExceptionBatchStoredProc.java:93)
com.csfb.fao.rds.rfi.common.dao.EarlyExceptionDAOImpl.saveEarlyExceptionBatch(EarlyExceptionDAOImpl.java:34)
com.csfb.fao.rds.rfi.application.rulesengine.RulesEngine.saveEarlyExceptions(RulesEngine.java:302)
com.csfb.fao.rds.rfi.application.rulesengine.RulesEngine.executeRules(RulesEngine.java:209)
com.csfb.fao.rds.rfi.application.rulesengine.RulesEngine.onMessage(RulesEngine.java:97)
com.csfb.fao.rds.feeds.process.BaseWorkerMDB.onMessage(BaseWorkerMDB.java:518)
weblogic.ejb.container.internal.MDListener.execute(MDListener.java:466)
weblogic.ejb.container.internal.MDListener.transactionalOnMessage(MDListener.java:371)
weblogic.ejb.container.internal.MDListener.onMessage(MDListener.java:327)
weblogic.jms.client.JMSSession.onMessage(JMSSession.java:4547)
weblogic.jms.client.JMSSession.execute(JMSSession.java:4233)
weblogic.jms.client.JMSSession.executeMessage(JMSSession.java:3709)
weblogic.jms.client.JMSSession.access$000(JMSSession.java:114)
weblogic.jms.client.JMSSession$UseForRunnable.run(JMSSession.java:5058)
weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516)
weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
Looking at the ARRAY.toBytes() method:
public byte[] toBytes()
throws SQLException
synchronized (getInternalConnection())
return this.descriptor.toBytes(this, this.enableBuffering);
..., it synchronizes on the following method (getInternalConnection() -> getPhysicalConnection()):
oracle.jdbc.internal.OracleConnection getPhysicalConnection()
if (this.physicalConnection == null)
try
this.physicalConnection = ((oracle.jdbc.internal.OracleConnection)new OracleDriver().defaultConnection());
catch (SQLException localSQLException)
return this.physicalConnection;
defaultConnection() does the following:
public Connection defaultConnection()
throws SQLException
if ((defaultConn == null) || (defaultConn.isClosed()))
synchronized (OracleDriver.class)
if ((defaultConn == null) || (defaultConn.isClosed()))
defaultConn = connect("jdbc:oracle:kprb:", new Properties());
return defaultConn;
So there's synchronizations on the connection instance and OracleDriver.class object... I can't see how this can deadlock. To get to the point of needing the lock on OracleDriver.class, the thread would already have the lock on the connection instance.... clearly I'm missing something.
Thanks
Edited by: 928154 on 17-Apr-2012 03:42Welcome to the forum. If you want help, at least try to think where to post a question and look for a forum that matches the topic. Lets examine what you have:
- its Weblogic, so if you would ask a non-programming related question anywhere it would be in the Weblogic forum
- HOWEVER, if you check the top of the stacktrace, you'll see that the problem stems from the JDBC driver, so a JDBC related forum would be a closer match
For future reference, Weblogic specific questions should go here: https://forums.oracle.com/forums/category.jspa?categoryID=193
and JDBC/OJDBC driver related questions should go here: Java Database Connectivity (JDBC)
Final tip: use \ tags to post code so it is readable. -
How to create oracle.sql.array
I need to create an oracle.sql.array to pass in my custom objects array to the database. I know you can create it using the ArrayDescriptor class but the problem with that is the connection object is need.
I am using the writeSql() method of the SQLData interface. I therefore dont have the connection object. Any ideas?haha
you misunderstand. i have in my code:
<code>
// update the organisation
public boolean setOrganisation(Organisation pOrg) {
Organisation org = pOrg;
OracleCallableStatement callStat = null;
Connection conn = null;
boolean OK = false;
try {
conn = getConnection(getUserName());
pOrg.setConnection(conn);
callStat = (OracleCallableStatement) conn.prepareCall("{call p_cmt.update_organisation(?)}");
callStat.setObject(1, org);
callStat.execute();
OK = true;
} catch (Exception e) {
logger.severe("error writing organisation with id " + org.getId() + ". " + e);
} finally {
cleanUpConnections(conn, callStat);
return OK;
</code>
This writes the object organisation to the database. Now in the class organisation i have the following method which is called automatically when writing the organisation object to the database:
<code>
public void writeSQL(SQLOutput p_stream) throws SQLException {
p_stream.writeInt(id);
p_stream.writeObject(country);
if (finIndexArr == null)
finIndexArr = new ListElement[0];
ArrayDescriptor af = ArrayDescriptor.createDescriptor(
ObjectMapper.elementList, conn);
ARRAY arr = new ARRAY(af, conn, finIndexArr);
p_stream.writeArray(arr);
</code>
The problem is the last bit. To put the finIndexArr into an array i need the connection object. So i have to pass into the organisation object the connection object which seems unneccessary and pointless to me. I was just looking at an alternative way of creating the array without the need of the connection object. Since the setOrganisation() above has the connection to the database i dont see why i need to specify it in the array as well -
PL/SQL array passed to SQL IN
Hi,
I have a PL/SQL array which type is defined like this:
create or replace type type_id_array as table of number(6, 3);
then i create a variable and initilaize:
var_1 type_id_array;
var_1 := .....
then i have a select statement.
select * from table t where t.id in(var_1)
That's it, i want to use the array in an SQL in. This seems not possible.
Can you explain why? Any alternate solutions?
Thanksuser610868 wrote:
That's it, i want to use the array in an SQL in. This seems not possible.
Can you explain why? Any alternate solutions?SQL supports set commands specifically for arrays (in addition to the using the TABLE() method mentioned). For example:
SQL> create or replace type TNumbers is table of number;
2 /
Type created.
SQL>
SQL> declare
2 numList TNumbers;
3 cnt integer;
4 begin
5 numList := new TNumbers(1,2,3,4,5,6,7);
6 select
7 count(*) into cnt
8 from user_objects
9 where TNumbers(object_id) member of numList;
10 DBMS_OUTPUT.put_line( 'cnt='||cnt );
11 end;
12 /
cnt=0
PL/SQL procedure successfully completed.Obviously there are performance considerations when using arrays/collections in SQL. So before choosing a method, evaluate the performance. -
Problem passing oracle.sql.ARRAY to Oracle
I am having ClassCastException when I try to pass a oracle.sql.ARRAY to a Oracle Package.
Here is my code:
PreparedStatement stmt = null;
String strArray[] = { "1,2,3,4,5" };
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "TEST_PAC_1.TEST_COLL_2", dbConnection );
//encounter Exception on the line below.
ARRAY array_to_pass = new ARRAY( descriptor, dbConnection, strArray );
String queryStr = "begin TEST_PAC_1.TEST_PROC_2(?); end;";
stmt = dbConnection.prepareStatement(queryStr);
stmt.setArray( 1, array_to_pass );
stmt.execute();
I understand that oracle.sql.ARRAY has been replaced by weblogic.jdbc.vendor.oracle.OracleArray in Weblogic.
MY QUESTION IS: HOW DO I INSERT MY STRING ARRAY INTO THE OracleArray and pass it to the plsql.
Really frustrated searching through the forums for the whole day,
Thanks,Try this if you are at weblogic 8.1:
Connection con = getConnectionFromDataSource();
Connection vendorConnection = ((WLConnection)con).getVendorConnection();
// use direct oracle connection.
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "TEST_PAC_1.TEST_COLL_2", dbConnection );
vendorConnection.close();
Beware that you should be very careful as you are going to use a direct vendor
connection.
The better aproach is to pass the string array as a delimited string to your storad
procedure and parse it in the SP - then you don't have to mess up with vendor-specific
handling.
Hope this helps.
Regards,
Slava Imeshev
"Daddy Daddy" <[email protected]> wrote in message news:24349835.1097143668312.JavaMail.root@jserv5...
I am having ClassCastException when I try to pass a oracle.sql.ARRAY to a Oracle Package.
Here is my code:
PreparedStatement stmt = null;
String strArray[] = { "1,2,3,4,5" };
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "TEST_PAC_1.TEST_COLL_2", dbConnection );
//encounter Exception on the line below.
ARRAY array_to_pass = new ARRAY( descriptor, dbConnection, strArray );
String queryStr = "begin TEST_PAC_1.TEST_PROC_2(?); end;";
stmt = dbConnection.prepareStatement(queryStr);
stmt.setArray( 1, array_to_pass );
stmt.execute();
I understand that oracle.sql.ARRAY has been replaced by weblogic.jdbc.vendor.oracle.OracleArray in Weblogic.
MY QUESTION IS: HOW DO I INSERT MY STRING ARRAY INTO THE OracleArray and pass it to the plsql.
Really frustrated searching through the forums for the whole day,
Thanks, -
Hello All,
Here is the issue description. Our application uses Oracle Object Types and LIST. We deployed our application on QA environment which has Oracle 10g. Application runs fine...no issues. Now we moved to UAT. UAT environment is same as QA environment and DBA have created replica of QA database.
Now WAR file which works fine with QA database , somehow doesnt work with UAT database. Application throws following exception when code tries to call getArray() on java.sql.Array.
We tried to point UAT weblogic to QA database and it worked fine.....but when we point UAT weblogic to UAT database , we get following exception. So we know that this is a database issue.
DBA claims that QA env database and UAT env database are same.
Can anybody please tell me what wrong here? What setting is not done on UAT database which is done on QA?
java.sql.SQLException: Internal Error at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:162) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:227) at oracle.jdbc.oracore.OracleTypeCOLLECTION.initCollElemTypeName(OracleTypeCOLLECTION.java:975) at oracle.jdbc.oracore.OracleTypeCOLLECTION.getAttributeType(OracleTypeCOLLECTION.java:1005) at oracle.jdbc.oracore.OracleNamedType.getFullName(OracleNamedType.java:96) at oracle.jdbc.oracore.OracleTypeADT.createStructDescriptor(OracleTypeADT.java:1958) at oracle.jdbc.oracore.OracleTypeADT.unpickle81(OracleTypeADT.java:1432) at oracle.jdbc.oracore.OracleTypeUPT.unpickle81UPT(OracleTypeUPT.java:426) at oracle.jdbc.oracore.OracleTypeUPT.unpickle81rec(OracleTypeUPT.java:383) at oracle.jdbc.oracore.OracleTypeCOLLECTION.unpickle81_imgBody_elems(OracleTypeCOLLECTION.java:928) at oracle.jdbc.oracore.OracleTypeCOLLECTION.unpickle81_imgBody(OracleTypeCOLLECTION.java:872) at oracle.jdbc.oracore.OracleTypeCOLLECTION.unpickle81(OracleTypeCOLLECTION.java:692) at oracle.jdbc.oracore.OracleTypeCOLLECTION._unlinearize(OracleTypeCOLLECTION.java:217) at oracle.jdbc.oracore.OracleTypeCOLLECTION.unlinearize(OracleTypeCOLLECTION.java:189) at oracle.sql.ArrayDescriptor.toJavaArray(ArrayDescriptor.java:663) at oracle.sql.ARRAY.getArray(ARRAY.java:282) at weblogic.jdbc.wrapper.Array_oracle_sql_ARRAY.getArray(Unknown Source)
Please help.425260 wrote:
This can happen if you use the oracle.sql.ARRAY class with WebLogic.
WebLogic wraps oracle.sql.ARRAY with its own class (i.e. weblogic.jdbc.wrapper.Array_oracle_sql_ARRAY). The easiest solution is to replace oracle.sql.ARRAY with the JDBC standard java.sql.Array.
<PRE class=jive-pre><CODE class="jive-code jive-java">Object[] items = (Object[])array.getArray();
<FONT color=navy><B>if</B></FONT> (items.length > 0) <FONT color=navy>{</FONT>
<FONT color=navy><B>for</B></FONT> (<FONT color=navy><B>int</B></FONT> i = 0; i < items.length; i++) <FONT color=navy>{</FONT>
Object arrayItem = items;
<FONT color=navy>}</FONT>
<FONT color=navy>}</FONT>
</CODE></PRE>
The <B>array</B> object is a java.sql.Array. Here no unwrapping of the WebLogic wrapper is needed.
If you absolutely need the oracle.sql.ARRAY class than you must use an <B>unwrap</B> API on the WebLogic wrapper class.
<PRE class=jive-pre><CODE class="jive-code jive-java"><FONT color=navy><B>if</B></FONT> (object <FONT color=navy><B>instanceof</B></FONT> weblogic.jdbc.wrapper.Array)
array = (ARRAY) ( ((weblogic.jdbc.wrapper.Array)object).unwrap(Class.forName(<FONT color=red>"oracle.sql.ARRAY"</FONT>)) );
<FONT color=navy><B>else</B></FONT>
array = (ARRAY) object;
</CODE></PRE>
Here, <B>array</B> is an oracle.sql.ARRAY. Try to see if this <A class=bodylinkwhite href="http://www.software-to-convert.com/3gp-conversion-software/3gp-to-myspace-video-software.html"><FONT face=tahoma,verdana,sans-serif color=#000 size=1>helps</FONT></A>. Good luck.
Thanks for your explanation! It's very valuable, It is exactly what I need, I understand this part.
Maybe you are looking for
-
Bouncing off the wall: Problems with passing/using pointers to classes
I have a mostly completed "msPaint" (=assigment) program that is driving me nuts!!! 1. First shape you draw doesn't appear. 1.5 Draw a shape by clicking twice on Panel, can change shape, color, fill with what buttons you see. 2. Subsequently only the
-
Netflow is not showing on prime infra 1.2 and also reports are not generating
Hi friends, I add my router to cisco prime for netflow and configured it by temelate as mentioned by cisco in deployment guide. I got netfloe till last friday but today i am getting anyflow on prime. second I am not able to generate raw netflow. how
-
Reply by message instead of taking a call - automatically sends as iMessage?
I like the new reply by message feature when someone calls you and you can't answer it. But my phone keeps sending them automatically as iMessages, even to contacts who aren't on iPhones. Normally when I'm sending texts to these people they don't go
-
Hi Gurus, I am a certified BI guy with over 5 yrs experience & as of now I am still an individual contributor in my company. Now I have got an opportunity & time to learn SAP BPC & also I am interested. So I want to know how much would that be helpf
-
i have been using my express to run airtunes as well as an internet connection to my laptop. i had been gone over the weekend and when i turned my laptop on it couldn't find my network. i hadn't made any changes to the settings and i had used airport