使用JDBC从MSSQL服务器检索查询执行计划文本

时间:2016-07-15 17:47:24

标签: java sql-server jdbc

我有以下只返回语句本身的Java方法。如何使用JDBC检索MSSQL查询执行计划文本?

 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();
  }

环境: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

1 个答案:

答案 0 :(得分:0)

您是否看过以下帖子中的第一个示例: Get the query plan using jdbc PreparedStatement on sql server

它没有使用jtds,但我确定小调整可以为您提供您正在寻找的东西。