Callable Statement Exception
Hi,
I am very new to Java SQL Callable Statement.
The following is the program that i wrote to execute a Stored Procedure stored in MS SQL Server 2000.
In my program I am actually retrieving back the value that I've passed to the MS SQL Server.
========================================
import java.sql.*;
import java.sql.Types;
public class CallableTester
private Connection connection;
public CallableTester(Connection conn)
connection = conn;
public void executeInsert ()
CallableStatement stmt = null;
String sqlstmt;
int rows;
try {
sqlstmt = "{ ? = call product(?, ?, ?, ?) }";
stmt = connection.prepareCall(sqlstmt);
stmt.setString(1, "61");
stmt.setString(2, "62");
stmt.setString(3, "63");
stmt.setString(4, "67");
stmt.registerOutParameter(1, Types.VARCHAR);
stmt.executeUpdate();
connection.commit();
System.out.println("The value inserted are " + stmt.getString(1));
stmt.close();
System.out.println(sqlstmt);
catch (Exception e){
e.printStackTrace();
=========================================
The is no syntax error.
When I run the program, I've got the following exception
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]COUNT field incorrect
or syntax error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6106)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:6263)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:2567)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedState
ment.java:217)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPrepare
dStatement.java:139)
at CallableTester.executeInsert(CallableTester.java:38)
at DatabaseConnection.makeConnection(DatabaseConnection.java:22)
at Start.main(Start.java:16)
=========================================
My database has a table named Product with the following fields and properties.
Field id of type varchar
Field name of type varchar
Field costPrice of type decimal
Field sellPrice of type decimal.
=========================================
The stored procedure for this table is
CREATE PROCEDURE product @id varchar(8) = 8, @name varchar(50) = "productName", @costprice decimal = 88, @sellprice decimal =168 AS
INSERT INTO PRODUCT VALUES(@id, @name, @costprice, @sellprice, @desc)
GO
=========================================
Can anyone please to help me? I have been trying to solve this problem few days but I really can't.
Your help will be appreciated.
Thank you very much.
I've reproduced your code with some modifications to make it work, I've tested it against a Sybase DB which is close enough to MS SQL Server.
First the procedure. Note that I create and write to a temp table you can ignore this.
create proc dmjtest
@id varchar(8) = '8',
@name varchar(50) = 'Dave Jenkins',
@costPrice decimal = 1.23,
@sellPrice decimal = 4.56
as
begin
declare @rc int
select @rc = 0
create table #t (
id varchar(8),
name varchar(50),
costPrice decimal,
sellPrice decimal
insert #t values (@id, @name, @costPrice, @sellPrice)
if @@error = 0 select @rc = 1
drop table #t
return @rc
endNow for the java code
import java.sql.*;
import java.sql.Types;
public class CallableTester
private Connection connection;
public CallableTester(Connection conn) {
connection = conn;
public void executeInsert () {
CallableStatement stmt = null;
String sqlstmt;
int rows;
try {
stmt = connection.prepareCall("{ ? = call dmjtest(?, ?, ?, ?) }");
stmt.registerOutParameter(1, Types.INTEGER);
stmt.setString(2, "1");
stmt.setString(3, "product 1");
stmt.setDouble(4, 63.0);
stmt.setDouble(5, 67.0);
stmt.executeUpdate();
connection.commit();
System.out.println("The return value is " + stmt.getInt(1));
stmt.close();
catch (Exception e){
e.printStackTrace();
}
Similar Messages
-
Callable Statement throws exception..pls help
When I use Callable Statement calling my function which returns Y if person is employee or nothing if not I get this error..
Procedure not createdORA-06550: line 1, column 22:
PLS-00103: Encountered the symbol "CHCK_EMP_STATUS" when expecting one of
the following:
. ( * @ % & = - + ; < / > at in mod not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like
between is null is not || is dangling
The symbol "." was substituted for "CHCK_EMP_STATUS" to continue.
Here is my code..
import java.sql.*;
import java.io.*;
public class FunctionTest
public static void main(String args[])
Connection conn = null;
CallableStatement stmt = null;
ResultSet rs=null;
try
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("........");
stmt = conn.prepareCall("{call function chck_emp_status(?,?)}");
stmt.setString(1,"137897");
stmt.registerOutParameter(2,Types.VARCHAR);
stmt.execute();
String s = stmt.getString(1);
stmt.close();
conn.commit();
conn.close();
}//try
catch(Exception e)
System.out.println("Procedure not created"+e.getMessage());
finally
}//main
Please help...This is the function
CREATE OR REPLACE function chck_emp_status (id number) return varchar2
as
emp_id number;
results varchar(2);
cursor emp_status is
select id
from emp
where emp_status = 'A'
and emp_id = id;
begin
open emp_status;
fetch emp_status into emp_id;
if emp_id%notfound THEN
results := '';
else
results := 'Y';
end if;
close emp_id;
return results;
end; -
Please, Not getting result set from callable statement (Code posted)
I am posting some simple code which should get a ResultSet from a CallableStatement object using the executeQuery() Method.
It is returning "No RsultSet was produced"
If I modify the code and simply output the CallableableStatement using its executeUpdate() then getString() methods it works fine. Anything obviously wrong with this bit of code? Thanks.
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import db.util.query.*;
import db.util.pool.*;
public class oracle extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
Connection con = ConnectionFactory.getConnection();
CallableStatement cs = null;
ResultSet rs = null;
int intID = 1;
try{
cs = con.prepareCall("{? = call test1(?)}");
cs.registerOutParameter(1, java.sql.Types.VARCHAR);
cs.setInt(2,intID);
/*These lines work on their own
*cs.executeUpdate();
*out.println("Name is : " + cs.getString(1));
//this code is what is not working...hmm
rs = cs.executeQuery();
while(rs.next()){
out.println(rs.getString("name"));
rs.close();
cs.close();
//the rest of this works too.
ConnectionFactory.releaseConnection(con);
catch(SQLException e){
out.println(e.getMessage());
Here's the stored procedure. I'm just trying to do a simple test to return multiple rows. The table has numberous records with the same id which is being passed to the function.
create or replace function test1 ( strInputID IN testtable.id%type)
return varchar2
is
strOutputName testtable.name%type;
found_it EXCEPTION;
begin
select name into strOutputName from testtable
where id = strInputID;
raise found_it;
exception
when no_data_found
then
return null;
when found_it
then
return strOutputName;
end;I've posted the code...it's doing a select. I think the problem is that to return multiple rows I need to return a cursor. But I've run into problems with both the MS and Oracle Drivers.
All I really want to do is to query a database using a callable statement(function in oracle) which will return multiple rows which I can process. I have been trying to do this in a servlet.
I can do it successfully for one column from one row, but not multiple columns from mulitple rows.
I've been searchging for some good examples and am trying different things but can't seem to get it to work. -
Memory leak in Callable Statement
We are using Weblogic 6.1 and Oracle 8.1.7 for an application we are developing.
Usage of callable statement seems to be resulting an a memory leak. The program runs
in a loop and after processing 200 records, java.lang.outofMemory Exception is thrown
We are unable to figure out a reason for the same.
The code snippet is as below
try
//dbConn = ImportPODBConnect.getDBConnection(dsJNDIName, dsURL); //connect
to DB <br>
dbConn = DBConnect.getDBConnection(dsJNDIName, dsURL);
//query = POQueries.selectPO(poId); //get the required
query statement from the POQueries utility class
Print.log(" in getPO() ----> ********* before 1st stmt " + System.currentTimeMillis());
cstmt = dbConn.prepareCall("{ ? = call PO_HEADER_PROC(?)}");
cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.setFloat(2, poId);
// execute and retrieve the result set
cstmt.execute();
getPORs = (ResultSet)cstmt.getObject(1);
Print.log(" in getPO() ----> ********* after 1st stmt " + System.currentTimeMillis());
if (!getPORs.next()) //if nothing returned then
throw an exception
Print.log("Unable to get the required PO:" + poId);
throw new Exception("Unable to get the required PO:" + poId);
else //set all the variables
of the PO header objects from the result set
pohSl = new POHeaderSl();
pohSl.setOvUserName(getPORs.getString("OVA_USER_NAME"));
pohSl.setOvCompanyName(getPORs.getString("OVA_COMPANY_NAME"));
pohSl.setAgent(getPORs.getString("AGENT"));
pohSl.setApprovalCode(getPORs.getString("APPROVAL_CODE"));
pohSl.setBrand(getPORs.getString("BRAND"));
pohSl.setBusinessSegment(getPORs.getString("BUSINESS_SEGMENT"));
pohSl.setBusinessSubSegment(getPORs.getString("BUSINESS_SUB_SEGMENT"));
pohSl.setBuyDate(getPORs.getString("BUY_DATE"));
pohSl.setCareContentLabel(getPORs.getString("CARE_CONTENT_LABEL"));
pohSl.setCartonMarkings1(getPORs.getString("CARTON_MARKINGS_1"));
pohSl.setCartonMarkings2(getPORs.getString("CARTON_MARKINGS_2"));
pohSl.setCartonMarkings3(getPORs.getString("CARTON_MARKINGS_3"));
pohSl.setCartonMarkings4(getPORs.getString("CARTON_MARKINGS_4"));
pohSl.setComments(getPORs.getString("COMMENTS"));
pohSl.setCommissionPerUnit(getPORs.getString("COMMISSION_PER_UNIT"));
pohSl.setCompanyId(getPORs.getString("COMPANY_ID"));
pohSl.setCompulsoryString(getPORs.getString("COMPULSORY_STRING"));
pohSl.setConTimestamp(getPORs.getString("CON_TIMESTAMP"));
pohSl.setCurrency(getPORs.getString("CURRENCY"));
pohSl.setCustomerBillToNumber(getPORs.getString("CUSTOMER_BILL_TO_NUMBER"));
pohSl.setCustomerLcBank(getPORs.getString("CUSTOMER_LC_BANK"));;
pohSl.setCustomerLcDate(getPORs.getString("CUSTOMER_LC_DATE"));
pohSl.setCustomerLcExpiryDate(getPORs.getString("CUSTOMER_LC_EXPIRY_DATE"));
pohSl.setCustomerLcNumber(getPORs.getString("CUSTOMER_LC_NUMBER"));
pohSl.setCustomerPoNumber(getPORs.getString("CUSTOMER_PO_NUMBER"));
pohSl.setCustomerSaleDept(getPORs.getString("CUSTOMER_SALE_DEPT"));
pohSl.setCustomerShipToNumber(getPORs.getString("CUSTOMER_SHIP_TO_NUMBER"));
pohSl.setCustomerSo(getPORs.getString("CUSTOMER_SO"));
pohSl.setDateLastModifiedErp(getPORs.getString("DATE_LAST_MODIFIED_ERP"));
pohSl.setDateLastModifiedOv(getPORs.getString("DATE_LAST_MODIFIED_OV"));
pohSl.setDateOfActivation(getPORs.getString("DATE_OF_ACTIVATION"));
Print.log(" ******** inside getPO() ----- > ****** built Header" + System.currentTimeMillis()
if(getPORs != null)
getPORs.close();
getPORs = null;
if(cstmt != null)
Print.log("In the close");
cstmt.close();
cstmt = null;
catch (Exception e)
System.out.println(" in dataAccess.getPO() ----- > " + e.toString());
throw new Exception(e.toString()); //if there are any exceptions
then throw back the exceptions
finally //finally block to release any connections
and statement objects
if(getPORs != null)
getPORs.close();
getPORs = null;
if (pstmt!=null)
pstmt.close();
pstmt = null;
if (cstmt!=null)
cstmt.close();
cstmt = null;
if (dbConn!=null)
dbConn.close();
dbConn = null;
return poSl; //return the PO object
Can anyone help with this?hi
This may happen when you open resultset objects and not close them properly.
Try to ensure that, you should close the objects in individual try catch
blocks so that one failure will not cause other close's to be skipped.
You can try one more thing, I don't see you are using any LONG/ LONG
RAW/BLOB/CLOB columns from your code here. If the table which you are trying
to retrieve data from has this type of data you will benefit from using some
tuning parameters here and may be able to avoid out of memory exceptions,
take a look at the url,
http://e-docs.bea.com/wls/docs61/oracle/advanced.html#1158561
especially, try using,
weblobic.oci.selectBlobChunkSize and set it to something low. you can set
these properties on the connection pool.
sree
"Murali" <[email protected]> wrote in message
news:[email protected]...
>
>
We are using Weblogic 6.1 and Oracle 8.1.7 for an application we aredeveloping.
Usage of callable statement seems to be resulting an a memory leak. Theprogram runs
in a loop and after processing 200 records, java.lang.outofMemoryException is thrown
>
We are unable to figure out a reason for the same.
The code snippet is as below
try
//dbConn = ImportPODBConnect.getDBConnection(dsJNDIName, dsURL);//connect
to DB <br>
dbConn = DBConnect.getDBConnection(dsJNDIName, dsURL);
//query = POQueries.selectPO(poId); //getthe required
query statement from the POQueries utility class
Print.log(" in getPO() ----> ********* before 1st stmt " +System.currentTimeMillis());
>
cstmt = dbConn.prepareCall("{ ? = call PO_HEADER_PROC(?)}");
cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.setFloat(2, poId);
// execute and retrieve the result set
cstmt.execute();
getPORs = (ResultSet)cstmt.getObject(1);
Print.log(" in getPO() ----> ********* after 1st stmt " +System.currentTimeMillis());
>
if (!getPORs.next()) //if nothing returnedthen
throw an exception
Print.log("Unable to get the required PO:" + poId);
throw new Exception("Unable to get the required PO:" + poId);
else //set all thevariables
of the PO header objects from the result set
pohSl = new POHeaderSl();
pohSl.setOvUserName(getPORs.getString("OVA_USER_NAME"));
pohSl.setOvCompanyName(getPORs.getString("OVA_COMPANY_NAME"));
pohSl.setAgent(getPORs.getString("AGENT"));
pohSl.setApprovalCode(getPORs.getString("APPROVAL_CODE"));
pohSl.setBrand(getPORs.getString("BRAND"));
pohSl.setBusinessSegment(getPORs.getString("BUSINESS_SEGMENT"));
pohSl.setBusinessSubSegment(getPORs.getString("BUSINESS_SUB_SEGMENT"));
pohSl.setBuyDate(getPORs.getString("BUY_DATE"));
pohSl.setCareContentLabel(getPORs.getString("CARE_CONTENT_LABEL"));
pohSl.setCartonMarkings1(getPORs.getString("CARTON_MARKINGS_1"));
pohSl.setCartonMarkings2(getPORs.getString("CARTON_MARKINGS_2"));
pohSl.setCartonMarkings3(getPORs.getString("CARTON_MARKINGS_3"));
pohSl.setCartonMarkings4(getPORs.getString("CARTON_MARKINGS_4"));
pohSl.setComments(getPORs.getString("COMMENTS"));
pohSl.setCommissionPerUnit(getPORs.getString("COMMISSION_PER_UNIT"));
pohSl.setCompanyId(getPORs.getString("COMPANY_ID"));
pohSl.setCompulsoryString(getPORs.getString("COMPULSORY_STRING"));
pohSl.setConTimestamp(getPORs.getString("CON_TIMESTAMP"));
pohSl.setCurrency(getPORs.getString("CURRENCY"));
pohSl.setCustomerBillToNumber(getPORs.getString("CUSTOMER_BILL_TO_NUMBER"));
pohSl.setCustomerLcBank(getPORs.getString("CUSTOMER_LC_BANK"));;
pohSl.setCustomerLcDate(getPORs.getString("CUSTOMER_LC_DATE"));
pohSl.setCustomerLcExpiryDate(getPORs.getString("CUSTOMER_LC_EXPIRY_DATE"));
pohSl.setCustomerLcNumber(getPORs.getString("CUSTOMER_LC_NUMBER"));
pohSl.setCustomerPoNumber(getPORs.getString("CUSTOMER_PO_NUMBER"));
pohSl.setCustomerSaleDept(getPORs.getString("CUSTOMER_SALE_DEPT"));
pohSl.setCustomerShipToNumber(getPORs.getString("CUSTOMER_SHIP_TO_NUMBER"));
pohSl.setCustomerSo(getPORs.getString("CUSTOMER_SO"));
pohSl.setDateLastModifiedErp(getPORs.getString("DATE_LAST_MODIFIED_ERP"));
pohSl.setDateLastModifiedOv(getPORs.getString("DATE_LAST_MODIFIED_OV"));
pohSl.setDateOfActivation(getPORs.getString("DATE_OF_ACTIVATION"));
Print.log(" ******** inside getPO() ----- > ****** built Header" +System.currentTimeMillis()
if(getPORs != null)
getPORs.close();
getPORs = null;
if(cstmt != null)
Print.log("In the close");
cstmt.close();
cstmt = null;
catch (Exception e)
System.out.println(" in dataAccess.getPO() ----- > " + e.toString());
throw new Exception(e.toString()); //if there are anyexceptions
then throw back the exceptions
finally //finally block to release anyconnections
and statement objects
if(getPORs != null)
getPORs.close();
getPORs = null;
if (pstmt!=null)
pstmt.close();
pstmt = null;
if (cstmt!=null)
cstmt.close();
cstmt = null;
if (dbConn!=null)
dbConn.close();
dbConn = null;
return poSl; //return the PO object
Can anyone help with this? -
Problems with Callable Statement
Hi All,
I have a problem with the callable statement that contains stored procedure.Here main thing i want to know is that can a stored procedure can be used for a database like Access.Because i am using Access as a database here.In which i have created the table Students.
The table Students contains 3 fields they are name,amount & balance.
The program is compiling well but during the runtime it is showing an error:-
"Syntax error in Create Table" .
For ur reference i have posted the code:-
import java.io.*;
import java.sql.*;
public class CallStatDemo
public static void main(String arg[])
Connection con;
CallableStatement cs;
Driver dr;
String str1,str2;
int in1,in2;
double d1;
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:Ananth"); //the dsn name is Ananth
init(con);
if(con==null)
System.out.println("Connection not Established");
else
cs=con.prepareCall("{call Payment(?,?)}");
cs.setString(1,"Raman"); //name
cs.setString(2,"2000"); //amount
cs.execute();
catch(Exception e)
System.out.println("Error Message : "+e);
static void init(Connection con)
throws SQLException
Statement stmt = con.createStatement();
stmt.execute ("create or replace procedure Payment(name in text,amount in text)is " +
" begin"+
" update Students set balance=balance-amount where name =name;"+
"end Payment;");
stmt.close();
Thanx,
m.ananthuI have no clue if Access supports stored procedures, and this surely isn't related to JDBC at all. Did you check your Access documentation?
Your posted code does not contain any CREATE TABLE statement, so where do you get your error (which line)
Most probably Access does not support stored procedures. To verify that, you should execute your CREATE PROCEDURE statement from within Access, to verify that it is a supported statement. -
Hi all,
I have a stored procedure which executes in sql query analyzer in 2 seconds.
It executes without any error. after execution of the stored procedure i get near about 4000 records.
Now i am trying to call the stored procedure using the callable statement.
It hangs on the line :
callablestatement.prepareCall("{call myproc}");at this lines nothing happens, nor i get any kind of exception. but my page just hangs. and nothing happens.Hi
Do u write callablestatement.prepareCall or sqlConnection.prepareCall ();
Have a look at the syntax for this at the following link.
http://java.sun.com/j2se/1.3/docs/api/java/sql/CallableStatement.html
Further you need to register any out parameters using registerOutParameter ()
and use
callablestmt.execute () to execute your stored proc.
HTH, Do revert back.
VJ -
Calling a procedure/function in CO using Callable Statement
Hi,
Please help me in understanding this:
__method1__
BEGIN
:1 := Package.Function(
param1 => :2"
,param2 => :3"
,param3 => :4"
,param4 => :5"
END;
method2
BEGIN
Package.Function(:1, :2, :3, :4, :5);"
END;
Whats the significance of using method1?
I have seen the callable statements written as in method1 but, the parameters passed are not in order and not all params are passed.
When i tried writing similar code, I got "Invalid Column Index" exception. Please let me know how to overcome this.
ThanksHi,
You can call a function using Callable Statement as
public String checkprimarycontact(String pri_loc_id,String org_id,String party_id)
int p_location_id = 0;
int p_org_id = 0;
int p_party_id = 0;
p_location_id = Integer.parseInt(pri_loc_id);
p_org_id = Integer.parseInt(org_id);
p_party_id = Integer.parseInt(party_id);
String priflag = "";
try
Connection conn1 = getOADBTransaction().getJdbcConnection();
CallableStatement cstmt1 = conn1.prepareCall("{? = call GET_PRIMARY_FUNCTION(?,?,?)}");
cstmt1.registerOutParameter(1,Types.VARCHAR);
cstmt1.setInt(2,p_location_id);
cstmt1.setInt(3,p_org_id);
cstmt1.setInt(4,p_party_id);
cstmt1.execute();
priflag = cstmt1.getString(1);
catch(Exception e1)
e1.printStackTrace();
return priflag;
Thanks,
Gaurav -
Using A callable statement in java
Hi all im trying to get results back from the database using a callable statement the problem is that it is placing / infront of single quotes.I need to get rid of this because it's not returning anything
here is my code
CallableStatement statementOne;
statementOne = ComparitiveAnalysisGUI.conn.prepareCall("{call graphProc(?,?,?,?,?,?,?)}");
statementOne.setString(1,"\"date_format(calldate, '%Y-%m-%d H:59:59'),avg(billsec)\"");
statementOne.setString(2,"Clovercdr");
statementOne.setString(3,start);
statementOne.setString(4,end);
statementOne.setString(5,"Boksburg");
statementOne.setString(6,"\"billsec > 0 and Network = " + network + "\"");
statementOne.setString(7,"\"date_format(calldate, '%Y-%m-%d %H:M:S')\"");
System.out.println(statementOne.toString());
rs = statementOne.executeQuery();
the result of the println is
com.mysql.jdbc.CallableStatement@ec4a87: CALL graphProc('"date_format(calldate, \'%Y-%m-%d %H:59:59\'),avg(billsec)"','Clovercdr','\'2006-03-14 00:00:01\'','\'2006-03-14 23:59:59\'','Boksburg','"billsec > 0 and Network = \'SAMobile\'"','"date_format(calldate, \'%Y-%m-%d %H:M:S\')"')
as you can see quite a mess please help if you can get the statement to look as follows
CALL graphProc("date_format(calldate, '%Y-%m-%d %H:59:59'),avg(billsec)",'Clovercdr','2006-03-14 00:00:01','2006-03-14 23:59:59','Boksburg',"billsec > 0 and Network = 'SAMobile'","date_format(calldate, '%Y-%m-%d %H:M:S')")
thanks BrianOk in order to understand why I did what I did parhaps it would be best if you saw my Stored procedure
create procedure graphProc(col varchar(100),company varchar(20),startTime datetime,endTime datetime,branchName varchar(20),andSection varchar(200),groupSec varchar(100))
BEGIN
SET @stmt := CONCAT("SELECT ",col," from ",company," where calldate between '",startTime,"' and '",endTime,"' and branchName = '",branchName,"' and ",andSection," Group by ",groupSec);
PREPARE stmt1 from @stmt;
EXECUTE stmt1;
the call is for example
call graphProc("date_format(calldate, '%Y-%m-%d %H:59:59'),avg(billsec)",'Clovercdr','2006-03-01 00:00:01','2006-03-14 23:59:59','Boksburg',"billsec > 0 and date_format(calldate, '%k') BETWEEN 7 AND 19 and Network = 'SAMobile'","date_format(calldate, '%Y-%m-%d %H:M:S')")//
as you can see In MySQL the "date_format(calldate, '%Y-%m-%d %H:59:59'),avg(billsec)" has to be quoted like this, so it can recognise it as a single parameter, since , '%Y-%m-%d %H:59:59' is viewed as another parameter
thaks for your reply
Brian -
Return records from Stored Procedure to Callable Statement
Hi All,
I am createing a web application to display a students score card.
I have written a stored procedure in oracle that accepts the student roll number as input and returns a set of records as output containing the students scoring back to the JSP page where it has to be put into a table format.
how do i register the output type of "records" from the stored function in oracle in the "registerOutParameter" method of the "callable" statement in the JSP page.
if not by this way is there any method using which a "stored function/procedure" returning "record(s)" to the jsp page called using "callable" statement be retrieved to be used in the page. let me know any method other that writing a query for the database in the JSP page itself.I have a question for you:
If the stored procedure is doing nothing more than generating a set of results why are you even using one?
You could create a view or write a simple query like you mentioned.
If you're intent on going the stored procedure route, then I have a suggestion. Part of the JDBC 2.0 spec allows you to basically return an object from a CallableStatement. Its a little involved but can be done. An article that I ran across a while back really helped me to figure out how to do this. There URL to it is as follows:
http://www.fawcette.com/archives/premier/mgznarch/javapro/2000/03mar00/bs0003/bs0003.asp
Pay close attention to the last section of the article: Persistence of Structured Types.
Here's some important snippets of code:
String UDT_NAME = "SCHEMA_NAME.PRODUCT_TYPE_OBJ";
cstmt.setLong(1, value1);
cstmt.setLong(2, value2);
cstmt.setLong(3, value3);
// By updating the type map in the connection object
// the Driver will be able to convert the array being returned
// into an array of LikeProductsInfo[] objects.
java.util.Map map = cstmt.getConnection().getTypeMap();
map.put(UDT_NAME, ProductTypeObject.class);
super.cstmt.registerOutParameter(4, java.sql.Types.STRUCT, UDT_NAME);
* This is the class that is being mapped to the oracle object.
* There are two methods in the SQLData interface.
public class ProductTypeObject implements java.sql.SQLData, java.io.Serializable
* Implementation of method declared in the SQLData interface. This method
* is called by the JDBC driver when mapping the UDT, SCHEMA_NAME.Product_Type_Obj,
* to this class.
* The object being returned contains a slew of objects defined as tables,
* these are retrieved as java.sql.Array objects.
public void readSQL(SQLInput stream, String typeName) throws SQLException
String[] value1 = (String[])stream.readArray().getArray();
String[] value2 = (String[])stream.readArray().getArray();
public void writeSQL(SQLOutput stream) throws SQLException
}You'll also need to create Oracles Object. The specification for mine follows:
TYPE Detail_Type IS TABLE OF VARCHAR2(1024);
TYPE Product_Type_Obj AS OBJECT (
value1 Detail_Type,
value2 Detail_Type,
value3 Detail_Type,
value4 Detail_Type,
value5 Detail_Type,
value6 Detail_Type,
value7 Detail_Type,
value8 Detail_Type);Hope this helps,
Zac -
Invalid Cursor state Exception - Help required
Hi,
I'm having a web page(JSP), which is making use of 3 ResultSet objects. Using the first two, i'll populate two different Drop down list, with values from database(Access) while loading the page for first time.
Now if the user select any value from any (or both) of drop down list and clicks submit, i need to display all values in database, meeting the criteria from first & second drop down list. For this selection, i'm using the third ResultSet variable. While executing the query, i'm sure that 3rd ResultSet is returning some value. But when i try to retrieve the value to a string variable, i'm getting the Invalid cursor state exception.
Throughout the page, i haven't closed any of the ResultSet. When i closed the first and second ResultSets in the third function(where 3rd ResultSet is used), i'm not getting any value. Its returning like ResultSet closed.
Please help me to get this solved. It's very urgent because without this, i cannot proceed further. Please share your ideas.
Thanks in advace for your valuable helpIf you open a new resultset within the same statement, all previously opened will be closed.
Read the API docs, luke. -
How to get the returned value from Functions with Callable statement?
I was glad to find that stored procedures can be invoke with Java class code by the object of Callable statement like :
String stmt = "BEGIN departments_pkg.do_select(?,?,?); END;";
and getting the output variables by
populateAttribute(DEPARTMENTNAME,st.getString(2),true,false);
But i would like to get values returned from FUNCTION other than stored procedure, how can i achieve it? Thanks a lot!Here is my code
PROCESS BEFORE OUTPUT.
MODULE STATUS_1202.
MODULE subscreen_find.
CALL SUBSCREEN SUBSEARCH INCLUDING sy-cprog dynnr.
PROCESS AFTER INPUT.
MODULE USER_COMMAND_1202.
CALL SUBSCREEN SUBSEARCH.
MODULE subscreen_find.
case sy-ucomm.
when 'SELECTED'. "fcode
case 'ZSKILL_SEARCH'. "data element
when '01'. " value range
dynnr = 0110.
when '02'.
dynnr = 0111.
endcase.
endcase.
ENDMODULE.
kindly tell me what is wrong
Edited by: Raji Thomas on Feb 8, 2010 10:20 AM -
Parameter name passed in Set Callable Statement
Is it not possible to pass parameter name in the callable statement while using Oracle drivers for jk 1.4??
Thanks!Is it not possible to pass parameter name in the callable statement while using Oracle drivers for jk 1.4??
Thanks! -
Hi All,
I have a get the data from table using CALLABLE statement.The problem is that that column datatype is CHAR.Is there any statement in java for to set
CallableStatement cstmt=null;
cstmt.setChar() ----- is it correct?Sorry for mistyping, I meant:
Oracle CHAR type is mapped to Java String.
cstmt.setString() should do. -
How to pass Array of Java objects to Callable statement
Hi ,
I need to know how can I pass an array of objects to PL/SQL stored procedure using callable statement.
So I am having and array list of some object say xyz which has two attributes string and double type.
Now I need to pass this to a PL/SQL Procedure as IN parameter.
Now I have gone through some documentation for the same and found that we can use ArrayDescriptor tp create array (java.sql.ARRAY).
And we will use a record type from SQL to map this to our array of java objects.
So my question is how this mapping of java object's two attribute will be done to the TYPE in SQL? can we also pass this array as a package Table?
Please help
ThanksI seem to remember that that is in one of Oracle's online sample programs.
http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/index.html -
How it works (Calling Stored Procedure in DB2 Through Callable statement)
Can anyone Please tell me what exactly happens on calling ESP(External Stored Procedure) through Callable statement Database point of view and Callable point of view also.
eg:
CallableStatement cstmt = con.prepareCall(
"{call getTestData(?, ?)}");
cstmt .executeUpdate();
where getTestData is Stored Procedure in DB2.
Can anyone please guide me working on this scenario..
Message was edited by:
Nitin_GuptaCheck this post out:
http://forum.java.sun.com/thread.jspa?threadID=638768&messageID=3785982
But I think you should be getting results right? What do you mean you want it in a format other than resultset?
Maybe you are looking for
-
Windows Explorer Plug-In Set-Up for BeehiveOnline with External Resources
I have watched the video on the Window Explorer Plug-In and trying to set-up so that multiple individuals can easily access files that are uploaded and make changes by checking in and out. Problem is that I do not see the Beehive Sites when I open th
-
Where is the location of CmdLnLauncher.bat in 11.1.2?
Hi , I intend to automate the business rules so that they can be scheduled to run. According to what I found you can automate Business Rules using the Business Rule Commandline Launcher . I found the CmdLnLauncher.bat in a windows server for version
-
Long time lurker first time poster. You guys have solved almost every problem I've ever had with FCP. I've been searching for an exact answer and honestly I'm sick so I don't feel like reading through a ton of close answers to find exactly what I nee
-
What external drive for Time Machine?
Hi all, I just upgraded to Leopard and want to set up TM, so I have been looking at external drives. I have done some research, read the forums, and I am more confused than before! I think I want a desk model with FW connection. I keep reading how un
-
How to get filechooser without default design
Hi, while i am using jfilechooser i am getting the default design as follows [click here to view the default_design of filechooser|http://www.mediafire.com/imageview.php?quickkey=qzmknjzon5y] but i don't want above one i want new design as follows [c