Sql-server – ny way to retrieve “Messages” in SQL Server through JDBC

javajdbcsql server

By "Messages" I mean the Messages tab in the following figure, which includes "Warning", "n rows affected" and in the figure below, the execution time. In JDBC, ResultSet class is used to retrieve the "Results". Is there any way to get all the information in the "Message" tab through JDBC?

enter image description here

Best Answer

You can get most of those messages, but unfortunately not all. See my question on Stackoverflow regarding that.

In general those messages (e.g. messages from a PRINT statement) are returned as warnings on the Statement object by the JDBC driver. To retrieve them use Statement.getWarnings() in a loop:

Statement stmt = ...;
stmt.execute("some_procedure");

SQLWarning warning = stmt.getWarnings();

while (warning != null)
{
   System.out.println(warning.getMessage());
   warning = warning.getNextWarning();
}

I have seen some messages also being returned on the Connection instance rather than the Statement. If you don't see anything, try the above code with your Connection instance.