简体   繁体   中英

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)?

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.

EXPLAIN ( analyze on, format xml ) SELECT ...

This will give you explain output you can more easily work with in Java by manipulating it as XML.

An other example with PreparedStatement, this time.

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

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