简体   繁体   English

如何从 Postgres 获取查询计划信息到 JDBC

[英]How to get query plan information from Postgres into JDBC

I want to capture the cost numbers from the query plan you get when you 'Explain' a query.我想从您“解释”查询时获得的查询计划中获取成本数字。 Is there any way to get at this data inside of a Java ResultSet(or similar object)?有没有办法在 Java ResultSet(或类似对象)中获取这些数据?

Sure, just run it as a regular statement:当然,只需将其作为常规语句运行:

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("explain analyze select * from foo");
while (rs.next())
{
   System.out.println(rs.getString(1));
}

In addition to the answer supplied above, I would suggest that you make use of the ability to format EXPLAIN plans as XML in PostgreSQL 9.0 and later.除了上面提供的答案之外,我建议您在 PostgreSQL 9.0 及更高版本中利用将 EXPLAIN 计划格式化为 XML 的功能。

EXPLAIN ( analyze on, format xml ) SELECT ...解释(分析,格式化 xml) SELECT ...

This will give you explain output you can more easily work with in Java by manipulating it as XML.这将为您提供解释输出,通过将其作为 XML 进行操作,您可以更轻松地在 Java 中使用它。

An other example with PreparedStatement, this time.这次是 PreparedStatement 的另一个示例。

Like this:像这样:

PreparedStatement preparedStatement = connection.prepareStatement("EXPLAIN (ANALYZE true , VERBOSE true , BUFFERS true)" +
                "SELECT * FROM Table");

ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}

Or with a bind parameter:或者使用绑定参数:

PreparedStatement preparedStatement = connection.prepareStatement("EXPLAIN (ANALYZE true , VERBOSE true , BUFFERS true)" +
                "SELECT * FROM Player WHERE id = ?");

preparedStatement.setLong(1, 1);

ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
      System.out.println(resultSet.getString(1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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