简体   繁体   中英

Retrieve query execution plan text from a MSSQL server using JDBC

I have the following Java method that is only returning the statement itself. How can I retrieve the MSSQL query execution plan text using JDBC?

 public String explainStatementMssql(String sqlStatement) {
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    StringBuilder output = new StringBuilder();
    try {
      connection = Utilities.getConnection();
      connection.setAutoCommit(false);
      statement = connection.createStatement();
      statement.execute("SET SHOWPLAN_TEXT ON");
      statement.executeQuery(sqlStatement);
      rs = statement.getResultSet();
      while (rs.next()) {
        output.append(rs.getString(1)).append("\n");
      }
      statement.execute("SET SHOWPLAN_TEXT OFF");
      connection.commit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
      Utilities.close(rs, statement, connection);
    }
    return output.toString();
  }

Environment: java -version

java version "1.7.0_101"
OpenJDK Runtime Environment (IcedTea 2.6.6) (7u101-2.6.6-0ubuntu0.14.04.1)
OpenJDK 64-Bit Server VM (build 24.95-b01, mixed mode)
jtds-1.2.6.jar
Microsoft SQL Server 2012

Have you had a look at the first example in the following post: Get the query plan using jdbc PreparedStatement on sql server

It's not using jtds, but I'm sure minor tweaks should provide you with what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM