Oracle stored procedure to Java stored procedure
Hello,
I got a school assignement "Create a java stored procedure and call it out from JAVA program outside database".
I've done it, but in case of JAVA stored procedure I have the procedure written in PL/SQL.
PL/SQL procedure:
CREATE OR REPLACE PROCEDURE getDogInfo
(Dog_ID IN NUMBER, Dog_name OUT VARCHAR) AS
BEGIN
SELECT Name INTO Dog_name
FROM Dog_family
WHERE ID = Dog_ID;
END;
How do I convert it to JAVA stored procedure?
Maybe it's just plain stupid and I should keep it as PL/SQL? I don't know if I have done it right.
Also I don't know what to do with IN/OUT parameters in JAVA.
Could my procedure java class look something like this? I am aware that I have to make a PL/SQL function that is associated with JAVA method CALL, just asking about JAVA Class at the moment.
import java.sql.*;
import java.io.*;
public class Procedure {
public static void getDogInfo (int Dog_ID, String Dog_name)
throws SQLException
{ String sql =
"SELECT Dog_name INTO Name FROM Dog_family WHERE ID = Dog_ID";
try { Connection conn = DriverManager.getConnection("jdbc:default:connection:");
PreparedStatement apstmt = conn.prepareStatement(sql);
apstmt.setInt(1, Dog_ID);
apstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
ResultSet rset = apstmt.executeQuery();
rset.close();
apstmt.close(); //Connection close
catch (SQLException e) {System.err.println(e.getMessage());
My java program looks like this:
package client;
import java.sql.*;
public class JDBCPiemers {
static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver";
static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
static final String USER = "SYSTEM";
static final String PASS = "asdasd";
private String sql;
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn = null;
CallableStatement stmt = null;
try {
//Registering JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to database ...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Preparing command...");
String SQL = "{CALL getDogInfo (?, ?)}";
stmt = conn.prepareCall(SQL);
int Dog_ID = 4;
stmt.setInt(1,Dog_ID);
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
System.out.println("CALL of JAVA stored procedure ...");
// Executing SQL
stmt.execute();
//Using getXXX method
String Name = stmt.getString(2);
System.out.println("Printing results ...");
System.out.println("ID NR. " +Dog_ID + " is Dog with
a name '" + Name + "'" );
stmt.close();
conn.close(); }
catch(SQLException se) {
//JDBC Errors
se.printStackTrace(); }
catch(Exception e) {
//Errors Class.forName
e.printStackTrace(); }
finally {
//Clossing resurses
try {if(stmt!=null)
stmt.close(); }
catch(SQLException se2) {}
try {if(conn!=null)
conn.close(); }
catch(SQLException se) {se.printStackTrace(); }
//finally block end
} // try
System.out.println("Closing program."); }}
Similar Messages
-
Issue with Oracle.sql.NUMBER in Java Stored Procedure
When we try to make a call to the Oracle.sql.NUMBER(String) inside a java stored procedure and pass values from '01' to '09', it throws java.lang.StringIndexOutOfBoundsException: String index out of range: 3
We use Oracle 9.2.0.6 - JServer Release 9.2.0.6.0.
It works fine for other values. Please find below the code used for simulating the issue outside the application. Thanks.
create or replace and compile java source named testNumber as
import oracle.sql.NUMBER;
import java.sql.SQLException;
public class TestNumber
public static String convertNumber(String parm) {
NUMBER nTest;
try {
nTest = new NUMBER(parm);
return "TRUE";
}catch (SQLException sqle) {
return "FALSE";
create or replace function test_number (p_str in varchar2) return varchar2 as
language Java name 'TestNumber.convertNumber(java.lang.String) return
java.lang.String';
select test_number('05') from dual; - Throws exception ORA-29532: Java call terminated by uncaught Java exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 3
select test_number('5') from dual; - Works fine
select test_number('010') from dual; - Works fineSiva,
I'm only guessing, but it could be an Oracle bug, in which case I suggest checking with Oracle Support.
(You do have a support contract, don't you? ;-)
Did you try compiling and running your java class "TestNumber" outside the database?
Class "oracle.sql.NUMBER" should be in Oracle's JDBC driver, I believe.
Good Luck,
Avi. -
Procedure or Java Stored procedure to send message/xml/data to MQ Series Qu
Hi
Using a simple Oracle Procedure or Oracle's Java stored procedure, I would like to send data to MQ Queue. It would be great if someone can help me with a piece of sample code.
Thanks in Advance
-GVHi Prabhu, Vlad
This is the same question which i asked few days back.
Our Backend system, only understands ISO8583 message format. And since I work in a financial environment, I can only send and receive data using "socket" protocol (tcp/ip).
So, This is where I have stuck forever...
I create a BS. select "any xml" . Then, I select "socket" as protocol. and click on finish.
Then, I create a Proxy Service based on my BS.
But, where/how do I convert the input xml packet into an ISO8583 format and send it over to my backend system ???
salil -
Connecting to a non-oracle database (jdbc) from a java stored procedure
Does anyone know to configure the database to allow a connection to a non-oracle database from a Java Stored procedured, using JDBC?
Thank you in advance,
ChrisHi Chris,
I haven't tried it, and these are just some of my thoughts, but I
think you would need to load the JDBC driver for the other database
into the Oracle database (using the "loadjava" tool, of-course).
Then your java stored procedure should be able to instantiate the
third party JDBC driver and obtain a connection to the other database.
Hope this helps.
Good Luck,
Avi. -
How to retrieve 'long' column with 32K length in Java stored procedure
For some reasons, we are not using CLOB, BLOB, or BFILE to store large objects and I have to live with LONG. So I wrote a Java stored procedure to insert, select and manipulate a LONG column by retrieving the LONG into a java.lang.String class (which happens to be the Java class mapped to the LONG SQL datatype). It all works fine as long as the length of the value being retrieved is less than the magic figure of 32767 bytes (which is the restriction on LONG and VARCHAR2 datatype in PL/SQL as well). So looks like Oracle's implementation of the JVM limits String values to a max of 32767 bytes. Suggestions on how to overcome this limitation (other classes that you suggest or do I have to move to files)?
Thanks,
Jeet
nullthe jvm has nothing to do with it ...
this is a pol/sql limitation on parameters in stored procedures.
and java stored procedures require a clal spec that makes the j-s-p look like a pl/qsl stored proc. -
Java stored procedures connection context
In my Oracle database there are two java stored procedures:
A java stored procedure P1 having
Connection conn1 = DriverManager.getConnection("jdbc:default:connection")
and
a java stored procedure P2 having
Connection conn2 = DriverManager.getConnection("jdbc:default:connection")
P1 calls P2 using conn1.CallableStatement.
Here is the question: does P2 inherit the connection
context conn1 (so that actualy conn2 = conn1) or P2's transactional
scope is separate from P1's one?
Thanks,
-EugeneAFAIK, when you run Java in the database, for local SQL data access, there is only one default connection per session, P1 and P2 should share the same transaction context.
Kuassi -
How may one increase JVM/Java Stored Procedure Perfomance?
Hi all,
my question: How can one increase the performance of the Oracle JVM, especially of Java Stored Procedures?
I ask this because I did some performance analysis (and was horrified :):
I have a static Java method that'll need an average 15 ms to return - when executed locally.
The same code, uploaded to an Oracle10g instance and published as Java Stored Procedure will take awful *925 ms*.
I measured both times from within the method as shown below:
public class JSProc {
public static void doSomething() {
long start = System.currentTimeMillis();
// now comes the '15 ms'-code
long time = System.currentTimeMillis() - start;
That way, I'm not including any call spec overhead, network communication or whatever into the 925 ms. All in all the above procedure call will take about 1200 to 1500 ms until it returns to the client...
The hardware: both client/server computers have the same hardware, both use the JDK provided with the latest Oracle10g release; single difference: client is Win2K, server is Linux.
I would be immensely grateful for your suggestions concerning the possibilities to increase the JVM performance...
Greetings,
SamAs Avi suggested, subsequent calls of the procedure within the same session will reduce the execution time down to 40 ms in my testing environment.
But that doesn't change anything for the 'first call' - when I start a new client program that opens a new connection, the Java Stored Proc will again need about a second to return.
I wrote the procedure now in PL/SQL - it will return in less than 30 ms, subsequent calls will return in less than a ms. Guess what I'll use :)
I played around with the JAVA* configuration params, but, as expected, that doesn't change anything in terms of performance. According to documentation, it will only affect the amount of classes I can load into the server.
I just read that Oracle creates a new "little" JVM for every session, and I imagine that there's lot of method intercepting and things (the ominous AOP-code) to ensure transaction security.
That's why I come to the conclusion that I won't use Java Stored Procedures for classical "connect, execute, disconnect" client-server applications. It's like full braking on the freeway :) -
RETURN RESULT SET FROM JAVA STORED PROCEDURE
I'm calling a Oracle 8.1.5 java stored proc from PL/SQL and I
would like to send a Java result set to the calling function.
I havent found anyway to do this currently. Anyone else doing
anything like this and have a work around or know when/if it has
been fixed?
Mark
[email protected]
nullThis is not possible in Oracle 8i, will have to wait till Oracle 9i
-
How to compile Oracle java strored procedure in Putty
I have created a java strored procedure , which would be invoked by oracle function.
This java stored procedure is get compiled via SQL plus. While compiling by the use of putty , it shows lots of compilation error .
How to compile Oracle java strored procedure in Putty??You'll need to add the j2ee.jar to your classpath. Usually you'll have to add some jars from your app server to your classpath as well.
For example (using weblogic):
javac -classpath c:\java\j2ee\j2ee1.3.1\lib\j2ee.jar;c:\tools\appserver\weblogic\wl7.1\lib\weblogic.jar
HelloServlet.java -
[b]Java Stored Procedure generating ora-932 in Oracle 9i [/b]
Hi ,
I have written a Java Stored procedure. And I have written a wrapper function as bellow
FUNCTION "GENERATE_AC_EXCEL_REPORT_FN"
( refCursorCall VARCHAR2, fromDate Date, ToDate Date,
nsn VARCHAR2, period varchar2, site VARCHAR2,
vendor VARCHAR2, spotbuyType VARCHAR2, dataType, VARCHAR2 )
return number
as LANGUAGE java
NAME 'accountingExcelReports.excelPrinter( java.lang.String, java.sql.Date, java.sql.Date, java.lang.String,java.lang.String , java.lang.String,
java.lang.String, java.lang.String , java.lang.String) return int';
This function returns 1000 upon successful execution.
This used to execute fine in Oracle 8.1.7.
We installed Oracle 9i recently.
Server version is 9.2.0.2.1.
Jserver version is 9.2.0.2.0 .
Now The function call works fine for the first time. And When execute it for sencond time in the same Session,
The program is erring out saying inconsistent data typpes.
This is happening during passing parameters.
SQL> select
2 generate_ac_EXCEL_report_fn('Period', to_date('7-1-2002','MM-DD-YYYY'),
3 to_date('7-31-2002','MM-DD-YYYY'), NULL,
4 NULL, NULL, NULL, 'ALL' ,'SPOTBUY') from dual;
GENERATE_AC_EXCEL_REPORT_FN('PERIOD',TO_DATE('7-1-2002','MM-DD-YYYY'),TO_DATE('7-31-2002','MM-DD-YYY
1000
SQL> select
2 generate_ac_EXCEL_report_fn('Period', to_date('7-1-2002','MM-DD-YYYY'),
3 to_date('7-31-2002','MM-DD-YYYY'), NULL,
4 NULL, NULL, NULL, 'ALL' ,'SPOTBUY') from dual;
select
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected IN Conversion failed
And upon further testing, i noticed this happens when the dates are passed. If date parameters are nulled out, Then the program executes perfectly any number of times.
The same program worked fine in Oracle 8.1.6
Any ideas?
Please help.
Thanks,
SrinivasHi Srinivas,
you shouldn't be calling conn.close() and its not needed when using Server Side Internal driver. If you are calling conn.close, then .....
extract from JDBC user guide
If you do call the close() method, be aware of the following:
All connection instances obtained through the defaultConnection() method, which actually all reference the same connection object, will be closed and
unavailable for further use, with state and resource cleanup as appropriate. Executing defaultConnection() afterward would result in a new connection
object.
Even though the connection object is closed, the implicit connection to the database will not be closed.
http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/java.920/a96654/advanc.htm#1001042
Elango. -
URGENT: Java stored procedure on oracle 92 database is not working
Hi,
I am having an issue regarding java stored procedures. I have created a java class that uses the bouncycastleprovider ( bcprov-jdk13-141.jar ) to encrypt strings. I tested against the version of the java virtual machine that comes bundled with oracle and it works perfectly. I then used JDeveloper to load the class on the database with the resolve, noverify and order flags checked and it shows no errors but when I try to execute the stored procedure it throws the following exception:
java.lang.ExceptionInInitializerError:
java.lang.SecurityException: Cannot set up certs for trusted CAs: java.net.MalformedURLException: no protocol: US_export_policy.jar
at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
at javax.crypto.Cipher.a(DashoA6275)
at javax.crypto.Cipher.getInstance(DashoA6275)
at RijndaelEnhanced.encrypt(RijndaelEnhanced.java:57)
at RijndaelEnhanced.encrypt(RijndaelEnhanced.java:73)
I loaded jce1_2_2.jar, sunjce_provider.jar, bcprov-jdk13-141.jar. Also replaced the US_export_policy.jar, local_policy.jar with the unrestrictive version. I add the security provider dinamically with a call to Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);
I also did a select on the user_objects table and all the classes are in VALID status.
When I run my application using the java virtual machine that is located under C:\Oracle\oracli9i\jdk\jre\bin directory it works fine but when I try to execute on the database it won't work. I found a bug that was if the jce1_2_1.jar file existed in the C:\Oracle\oracli9i\jdk\jre\lib\ext directory ( even if it's extension is renamed ) it won't work because the certification file had expired but I don't know if this has anything to do with this error.
Am I missing something?
Please I need an urgent solution to this problem.
Thanks in advance.
Bruno OliveiraSomeoneElse wrote:
Waaaaahhhhhhh!I was just thinking the same thing.... ya beat me to it...
To the OP:
As an up and coming DB Developer who now works for a small tech firm straight outta college, I can tell you for sure that you will definitely not get anywhere in your impatient life... look behind your back you miserable dude, your job might be in danger since ya got a bad attitude AND you can't figure out an error you are getting from a Java SP. So instead of helping you, I am going to simply tell you how you SHOULD act in a community of practice.
1. Be nice when looking for help
2. BE NICE WHEN LOOKING FOR HELP!!!
Pretty simple right?
Know what else is really simple? Looking at the topics of each board to make sure ya post in the right board! You people disgust me; somehow getting by in your professional career acting the way you do. I sure hope your "online" persona isn't a reflection of your real attitude towards people, almost pathetic and extremely immature.
Sorry bout the rant, it is Friday, I know :) Didn't get my coffee this morning. Have a good one all!
-Tim -
Issue with sending mail through java stored procedure in Oracle
Hello
I am using Oracle 9i DB. I created a java stored procedure to send mail using the code given below. The java class works fine standalone. When its run from Java, mail is sent as desired. But when the java stored procedure is called from pl/sql "Must issue a STARTTLS command first" error is thrown. Please let me know if am missing something. Tried the same code in 11.2.0.2 DB and got the same error
Error:
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. va6sm31201010igc.6
Code for creating java stored procedure: (T1 is the table created for debugging)
==================================================
create or replace and compile java source named "MailUtil1" AS
import java.util.Enumeration;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtil1 {
public static void sendMailwithSTARTTLS(String host, //smtp.projectp.com
String from, //sender mail id
String fromPwd,//sender mail pwd
String port,//587
String to,//recepient email ids
String cc,
String subject,
String messageBody) {
try{
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "True"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", fromPwd);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
#sql { insert into t1 (c1) values ('1'||:host)};
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
#sql { insert into t1 (c1) values ('2')};
InternetAddress[] toAddress = new InternetAddress[1];
// To get the array of addresses
for( int i=0; i < toAddress.length; i++ ) { // changed from a while loop
toAddress[i] = new InternetAddress(to);
//System.out.println(Message.RecipientType.TO);
for( int i=0; i < toAddress.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, toAddress);
if (cc!=null) {
InternetAddress [] ccAddress = new InternetAddress[1];
for(int j=0;j<ccAddress.length;j++){
ccAddress[j] = new InternetAddress(cc);
for (int j=0;j<ccAddress.length;j++){
message.addRecipient(Message.RecipientType.CC, ccAddress[j]);
message.setSubject(subject);
message.setText(messageBody);
message.saveChanges();
#sql { insert into t1 (c1) values ('3')};
Enumeration en = message.getAllHeaderLines();
String token;
while(en.hasMoreElements()){
token ="E:"+en.nextElement().toString();
#sql { insert into t1 (c1) values (:token)};
token ="ConTyp:"+message.getContentType();
#sql { insert into t1 (c1) values (:token)};
token = "Encod:"+message.getEncoding();
#sql { insert into t1 (c1) values (:token)};
token = "Con:"+message.getContent();
#sql { insert into t1 (c1) values (:token)};
Transport transport = session.getTransport("smtp");
#sql { insert into t1 (c1) values ('3.1')};
transport.connect(host, from, fromPwd);
#sql { insert into t1 (c1) values ('3.2')};
transport.sendMessage(message, message.getAllRecipients());
#sql { insert into t1 (c1) values ('3.3')};
transport.close();
#sql { insert into t1 (c1) values ('4')};
catch(Exception e){
e.printStackTrace();
String ex= e.toString();
try{
#sql { insert into t1 (c1) values (:ex)};
catch(Exception e1)
Edited by: user12050615 on Jan 16, 2012 12:18 AMHello,
Thanks for the reply. Actually I have seen that post before creating this thread. I thought that I could make use of java mail to work around this problem. I created a java class that succesfully sends mail to SSL host. I tried to call this java class from pl-sql through java stored procedure. That did not work
So, is this not supported in Oracle ? Please note that I have tested this in both 9i and 11g , in both the versions I got the error. You can refer to the code in the above post.
Thanks
Srikanth
Edited by: user12050615 on Jan 16, 2012 12:17 AM -
Java stored procedure problem(oracle db)
HI,
we have a java stored procedure with the following definition, and that works as we want it to:
CREATE OR REPLACE FUNCTION processBulletin(in_varchar VARCHAR2) RETURN VARCHAR2
AS LANGUAGE JAVA
NAME 'JavaParser.Bufr_Ingest.processBulletin(java.lang.String) return java.lang.String';
And the Java portion:
public static String processBulletin(String in_bull)
... do something with in_bull
The problem is that we've recently discovered that the 32767 size restiriction on the input parameter varchar2 is too small. I don't want to rewrite the entire Java procedure. I figured the simplest (or at least temporary)solution would be to have the Java procedure accept a CLOB, convert that clob to a string and continue as it would. I was hoping someone might be able to tell me if the following would be possible:
CREATE OR REPLACE FUNCTION processBulletin(in_clob CLOB) RETURN VARCHAR2
AS LANGUAGE JAVA
NAME 'JavaParser.Bufr_Ingest.processBulletin(oracle.sql.CLOB) return java.lang.String';
And the Java portion:
public static String processBulletin(oracle.sql.CLOB in_clob)
String in_bull = clob_in.getSubString(1, (int)clob_in.length());
... do something with in_bull
ThanksI don't know about Java stored procedures, but in JDBC you usually use streams to work with CLOBS. Here's Oracle JDBC Developers Guide, Working with LOBs
-
Problem in calling Oracle stored procedure from Java.
I am trying to invoke the Oracle stored procedure from Java. The procedure does not take any parameters and does not return anything. If I call it from SQL prompt it is working perfectly. I am calling it in my program as follows.
callable_stmt=con.prepareCall("{call pkg_name.proc_name()}");
callable_stmt.execute();
The problem is the control-of-flow is getting strucked in the second line I wrote. It is not giving any error also.
Please clarify me what's wrong with my code?
Seenu.And how long does the stored procedure take to run from your client machine when running it via sqlplus?
-
Problem in writting oracle stored procedure in java
Hi,
Can anybody please suggest me how can I access oracle stored procedure in Java.
Thanksplease find the examples in the below url.
http://javaalmanac.com/egs/java.sql/pkg.html
Maybe you are looking for
-
Error reading job logs of Apps server from Central Instance
Dear Gurus, We have newly installed system with one CI ( cluster environment) and 2 application Instances. Systems are recently installed by other team. I am looking into support part after handover. We have noticed below error while reading failed b
-
Deletion of multiple songs at one time on iPod Touch
Does anyone know a way to delete multiple song at one time on iPod Touch? For some reason, there is anywhere from 3-5 of each song in my library and I REALLY don't want to have to delete 2000 songs one by one! Please help!!!
-
Same output file in multiple directories.
Hi, I am working on a Proxy to File scenario where a target csv file is generated by PI. The requirement is that PI needs to generate a csv file and post that file in 4 separate directories of a same FTP server. I intend to do that using single comm
-
Want Firefox to open new links in current tab, not to open in new tab.
With one of the new updates, Firefox opens a new tab when going to a new link, rather than opening link in the current tab, the way it did in earlier versions. I know I can choose open new tab or open new window in Preferences, but I want to just ope
-
I keep getting message error 101, have tryed 3 times to download, on windows vista
i get message error 101, i've tryed to download 3 times now, with the same results every time. i'm using windows vista, any one have any ideas?