Callable Statement Syntax
I am using the callable statement to invoke a MS SQL Server stored procedure that will return a result set. I have several questions:
1) According to the Java documentation I should be using the following format for a prepareCall that will return a result paramater with 4 input paramaters:
{ ? = call SP_ABC(?, ?, ?, ?)}
In my particular case the stored procedure will return 14 pieces of data in a result set. Do I need to write code for 14 registerOutParameter fields? Is the syntax mentioned above accurate for the 14 pieces of data or do I need to repeat the question marks (?) 14 times? What shoud the syntax be for my prepareCall statement?
The ? in the sql syntax refer to variables passed to the procedure as either in or in/out parameters. You need to write code to register any OUT variables (including any return value).
The data returned from the SP will be returned as a ResultSet which is processed in the normal way.
So assuming that you have a procedure declared as:
create proc p @1 int, @2 int OUTPUT as ...then your code would look like this:
statement = connection.prepareCall("{?=call p (?,?}");
// register the return code
statement.registerOutParameter(1,Types.INTEGER);
// register the OUTPUT var @2
statement.registerOutParameter(3,Types.INTEGER);
// Set the input param @1
statement.setInt(2,0);
rs = statement.executeQuery();
// Get the return code
int rc = statement.getInt(1);
// Get the output param @2
int out = statement.getInt(3);
// process the result set
while(rs.next()) {...}Dave
Similar Messages
-
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();
} -
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 -
How to return Multiple ResultSets Using Callable Statement
hi everybody,
while i was working with callable statements i came across a problem of how to fetch Multiple Resultsets by means of Stored Procedures written for tables in Oracle.
If any one can help me, pls do help me with a detailed explanation, and if possible do get me a example source code too.
khumaarI have a similar problem with oracle and jdbc:
I want to send a sql query like:
sqlQuery = "select n1, n2 from table1; select n1, n2
from table2"
I used a prepared statement, but when I call
.execute(sqlQuery)
oracle doesn't like this,
can someone help on this?Try putting a begin/end around it. Play with the syntax first in sqlplus.
You do realize that you MUST extract using the syntax for extracting multiple result sets correct? It will NOT work as one result set. -
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 -
IF statement syntax in SQL script view
I need to include a "IF" condition in the "SELECT" section of my SQL script view.
I tried the following syntax's but I get the error 'Incorrect SQL syntax near 'IF'
1. IF(Revenue <> '0' AND Quantity <> '0', Revenue/Quantity, '0') AS Gross Price
2. IF(Revenue != '0' AND Quantity != '0', Revenue/Quantity, '0') AS Gross Price
3. IF(Revenue <> '0' AND Quantity <> '0' THEN Revenue/Quantity ELSE '0' END) AS Gross Price
4. IF(Revenue != '0' AND Quantity != '0' THEN Revenue/Quantity ELSE '0' END) AS Gross Price
My final SQL would read like follows:
SELECT field1, field2, IF(......) AS field3
FROM table1
Can anybody please help with the correct IF statement syntax to be used in the SQL script based view?Hi Lakshmi,
below is the syntax for IF statement.
IF <bool_expr1> THEN
<then_stmts1>
ELSEIF <bool_expr2>
THEN <then_stmts2>
[ELSE <else_stmts3>]
END IF
eg :
BEGIN
DECLARE found INT := 1;
SELECT count(*) INTO found FROM books WHERE isbn = :v_isbn;
IF :found = 0 THEN
INSERT INTO books VALUES (:v_isbn, 'In-Memory Data Management', 1, 1, '2011', 42.75, 'EUR');
ELSE
UPDATE books SET price = 42.75 WHERE isbn =:v_isbn;
END IF;
END;
Sreehari -
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. -
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. -
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? -
Error executing a callable statement on a pooled connection
Hi,
I have an Oracle function that returns a number:
create or replace function
S2B_STOP_STAGE (DOC_ID number, ST_ID number)
return number ...
and the following Java code:
Class.forName("weblogic.jdbc.pool.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:weblogic:pool:madrigalPool");
String sql = "{? = call S2B_STOP_STAGE(401,1002)}";
CallableStatement stmt = conn.prepareCall(sql);
stmt.registerOutParameter(1, Types.INTEGER);
stmt.execute(sql);
res = stmt.getInt(1);
When the execute(sql) statement is executed, a SQLException is thrown:
java.sql.SQLException: ORA-01008: not all variables bound
at weblogic.jdbc.pool.PreparedStatement.execute(PreparedStatement.java:121)
Does anybody have an idea about what may be wrong? I am using Oracle
8.1.6, the thin driver classes12-81620.zip, and WebLogic 6.0 sp2.
Thanks,
VladimirI found out what was wrong. I should have used execute() instead of execute(sql)
on the callable statement...
Sorry for the problem.
Vladimir
"vladimir" <[email protected]> wrote:
>
Hi,
I have an Oracle function that returns a number:
create or replace function
S2B_STOP_STAGE (DOC_ID number, ST_ID number)
return number ...
and the following Java code:
Class.forName("weblogic.jdbc.pool.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:weblogic:pool:madrigalPool");
String sql = "{? = call S2B_STOP_STAGE(401,1002)}";
CallableStatement stmt = conn.prepareCall(sql);
stmt.registerOutParameter(1, Types.INTEGER);
stmt.execute(sql);
res = stmt.getInt(1);
When the execute(sql) statement is executed, a SQLException is thrown:
java.sql.SQLException: ORA-01008: not all variables bound
at weblogic.jdbc.pool.PreparedStatement.execute(PreparedStatement.java:121)
Does anybody have an idea about what may be wrong? I am using Oracle
8.1.6, the thin driver classes12-81620.zip, and WebLogic 6.0 sp2.
Thanks,
Vladimir
Maybe you are looking for
-
How to fix the iphone 4s if it is the wrong carrier iphone 4s?
Just wondering if anyone has had this problem and how to fix it. Lets see in October 2012 I bought a brand new Iphone 4s. I had it less than a week when I sent it to Apple because it had already been updated to IOS 6 without my knowledge and the
-
I am unable to remember my password for my icloud email how do i reset it ?please
i have forgotten my icloud e mail password how do i get it reset please? i can get into my icloud main account but not sure how to reset my icloud email
-
How do I access the toolbar that offers dropdowns with firefox on my macbook pro computer screen
Mac OS X 10.6.8
-
1 Node/ Webcache Port 80/ Apps on Port 7778 and 8080
I have a machine with 3 aliases. Is it possible to bind multiple ports to webcache running on port 80 and depending on alias have it routed to the correct application and port? What I want is someone that enters http://app1 to go to port 7778 and htt
-
Test Script for Event driven function
Hi, i m new to this product. i have one doubt , is it possible to write test scripts for event driven functions ? if possible, could you please share some samples.? Thnk you. Bala.