Retrieve anonymous PLSQL block result

前端 未结 2 1476
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 14:45

I have some trouble retrieving the result of an anonymous PLSQL block in java.

Here is the block :

DECLARE
in_cnt_date DATE := \'&1\';
hv_cnt_id NUM         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-26 15:23

    It is because the implicit date conversion is failing. Add TO_DATE() instead of directly assigning the date string to a date variable. If java.sql.Date is used, the TO_DATE() is not required.

    The implicit conversion usually depends on the session's NLS_DATE_FORMAT.

    In your case in_cnt__date DATE := '&1' is the culprit. &1 will actually be attempted to convert into a date.. And hence the exception thrown!

    public static final String CONTEXT = "DECLARE in_cnt__date DATE := ? ;" +
    "hv_cnt_id NUMBER := 0; " +
    "BEGIN DBMS_OUTPUT.ENABLE (NULL); " +
    "INSERT INTO dt_contexts (CNT_ID, CNT_CONTEXT, CNT_TYPE, CNT_SOURCE, CNT_COMMENT, CNT_DATE, CNT_DATE_INSERT, CNT_DATE_UPDATE) " +
    "VALUES (0, 'EPE_CONTEXT', 'ROUTE', 'bdd', 'Built from ROUTE', in_cnt__date, SYSDATE, SYSDATE); " +
    "SELECT SEQ_DT_CNT_ID.CURRVAL INTO hv_cnt_id FROM DUAL; " +
    "? := hv_cnt_id;
    "EXCEPTION WHEN OTHERS THEN RAISE ; END;";
    

    And then,

    cs.setDate(1, (java.sql.Date) Route.datePrf);
    

    Will set the date for in_cnt__date;

    Finally, to retreive the values in hv_cnt_id The below is added to your PL/SQL block

    "? := hv_cnt_id;"
    

    And from JDBC, we get it like,

     cs.setDate(1, (java.sql.Date) Route.datePrf);
     cs.registerOutParameter(2, Types.NUMBER);
     cs.execute();
     contextId = cs.getInt(2);
    

提交回复
热议问题