-1

I have a stored procedure that produces output via various PRINT statements. I want to grab that output in Java, and I don't know how to do it. Can this be done at all?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Michael Robinson
  • 1,106
  • 3
  • 13
  • 40
  • I would just use `OUT` parameters in the procedure. – dan1st Jun 03 '21 at 20:20
  • old, but maybe still valid - no [you can't](https://stackoverflow.com/questions/29863135/getting-print-messages-from-sqlserver-to-java-application) – Nikki9696 Jun 03 '21 at 21:04
  • 1
    You sort of can in [ADO](https://learn.microsoft.com/en-us/troubleshoot/sql/connect/retrieve-values-stored-procedure) but really this is not intended as a way to return information to the client. – Dale K Jun 03 '21 at 21:16
  • `PRINT` is designed as a debugging tool, don't use it in production code – Charlieface Jun 04 '21 at 03:32

1 Answers1

0

The output of print statements is available via SQLWarnings, e.g.:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;

public class SQLDatabaseConnection {
    public static void main(String[] args) {
        String connectionUrl =
                "jdbc:sqlserver://YourServerName:1433;"
                        + "database=SomeDB;"
                        + "user=SomeUsername;"
                        + "password=S0meM4gic4lP4ssw0rd;"
                        + "encrypt=true;"
                        + "trustServerCertificate=true;"
                        + "loginTimeout=30;";

        ResultSet resultSet = null;

        try (Connection connection = DriverManager.getConnection(connectionUrl);
            Statement statement = connection.createStatement();) {

            resultSet = statement.executeQuery("print 'Hello, world!'; select getdate() as [Something]");
            while (resultSet.next()) {
                System.out.format("Result set: %s\n", resultSet.getString(1));
            }

            SQLWarning warning = statement.getWarnings();
            while (warning != null)
            {
                System.out.format("Warning: %s\n", warning.getMessage());
                warning = warning.getNextWarning();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Which outputs...

Result set: 2021-06-04 00:38:27.567
Warning: Hello, world!
AlwaysLearning
  • 7,915
  • 5
  • 27
  • 35