Search code examples
oraclejdbcsql-execution-plan

How to get Oracle execution plan xml through jdbc


I need to parse execution plans for queries and extract data out of them for my application. While this answer JDBC Oracle - Fetch explain plan for query helped me fetch a text execution plan through jdbc, it is not possible to parse the text output as the queries are runtime params. Below mentioned sample query returns the xml in "Sql Developer" but NOT through jdbc. I am using Oracle 11g XE with ojdbc6.jar driver. Why is this query not working via the jdbc api? Any help will be appreciated.

EXPLAIN PLAN SET STATEMENT_ID = '123' FOR select * from jobs where rownum < 3 order by job_id desc

SELECT dbms_xplan.build_plan_xml(statement_id => '123') AS XPLAN FROM dual;

Below is my java code:

    Driver d = (Driver) Class.forName("oracle.jdbc.OracleDriver").newInstance();
    Connection conn = d.connect("jdbc:oracle:thin:username/password@//localhost:1521/XE", new Properties());
    Statement statement1 = conn.createStatement(); 
    statement1.execute("explain plan set STATEMENT_ID = '"+ id + "' for " + query);
    statement1.executeQuery("select dbms_xplan.build_plan_xml(statement_id => '"+ id + "') AS XPLAN FROM dual");
    ResultSet resultSet = statement1.getResultSet();            
    while (resultSet.next()) {
        executionPlan = resultSet.getSQLXML(1).getString();
    }

Solution

  • I don't think the result is returned as a "real" JDBC XML type.

    Try

    resultSet.getString(1)
    

    instead

    If that doesn't work, try also to cast the result to a clob:

      executeQuery("select to_clob(dbms_xplan.build_plan_xml(....
    

    That definitely will require you to use getString(1) instead of getSQLXML()