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?
The output of print statements is available via SQLWarnings, eg:
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!
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.