2013-09-21 63 views
1

我有一個存儲過程我如何通過一個遊標作爲參數傳遞給存儲過程,並抓住它背在java中

CREATE OR REPLACE FUNCTION fun_retrieve_vector_receipt_payment_details(character varying, integer, character varying, character varying, character varying, refcursor) RETURNS refcursor AS 

這是我的java代碼

con.setAutoCommit(false); 
     String sql = "{call fun_retrieve_vector_receipt_payment_details(?,?,?,?,?,?)}"; 
     callableStatement = con.prepareCall(sql); 
     callableStatement.setString(1, "PAYMENT"); 
     callableStatement.setInt(2, 41); 
     callableStatement.setString(3, "2011-05-06"); 
     callableStatement.setString(4, "2013-05-06"); 
     callableStatement.setString(5, "Y"); 
     callableStatement.setObject(6, rs); 
     callableStatement.registerOutParameter(6, Types.OTHER); 

     callableStatement.execute(); 

     ResultSet resultSet = (ResultSet) callableStatement.getObject(6); 
     //   rs = callableStatement.executeQuery(); 
     boolean next = resultSet.next(); 
     if (next) 
     { 
      System.out.println(resultSet.getString(1)); 
     } 

爲什麼我得到結果集,作爲空值?
我應該通過refcursor作爲參數從java傳遞什麼?

我使用的Postgres作爲我的數據庫

+0

什麼是rs,你從哪裏取得它? –

回答

1

試試這個辦法:

Statement stmt = conn.createStatement(); 
stmt.execute("CREATE OR REPLACE FUNCTION " 
     +" fun_retrieve_vector_receipt_payment_details(x1 integer, x2 integer)" 
     + " RETURNS refcursor AS '" 
     + " DECLARE " 
     + " mycur refcursor; " 
     + " BEGIN " 
     + " OPEN mycur FOR SELECT x FROM generate_series(x1, x2) x; " 
     + " RETURN mycur; " 
     + " END;' language plpgsql"); 
stmt.close(); 

conn.setAutoCommit(false); 

CallableStatement proc = conn.prepareCall(
     "{ ? = call fun_retrieve_vector_receipt_payment_details(?, ? ) }"); 
proc.registerOutParameter(1, Types.OTHER); 
proc.setInt(2 , 13); 
proc.setInt(3 , 17); 
proc.execute(); 
ResultSet results = (ResultSet) proc.getObject(1); 
while (results.next()) { 
    System.out.println(results.getString(1)); 
} 

results.close(); 
proc.close(); 
conn.close(); 

Run ... 
13 
14 
15 
16 
17 
1

REFCURSOR是光標的名字 - 所以它是字符串。所以你必須得到一個這個名字,你可以把它作爲字符串傳遞給它:

 
postgres=# begin; 
BEGIN 
Time: 0.398 ms 
postgres=# declare xxx cursor for select * from f1; 
DECLARE CURSOR 
Time: 23.409 ms 
postgres=# select fx('xxx'); 
NOTICE: (10,20) 
NOTICE: (340,30) 
fx 
──── 

(1 row) 

commit; 

CREATE OR REPLACE FUNCTION public.fx(refcursor) 
RETURNS void 
LANGUAGE plpgsql 
AS $function$ 
declare r record; 
begin 
    while true 
    loop 
    fetch $1 into r; 
    exit when not found; 
    raise notice '%', r; 
    end loop; 
end; 
$function$ 
相關問題