Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to display PRINT results with SQL server JDBC driver?

If my stored procedure has a print statement inside it:

print 'message'

Is there a way to fetch the output in java program that connects to SQL Server 2008 through JDBC?

Also, is there a danger that print messages left for debugging would shutdown connection when called from JDBC application?

like image 962
Alexander Pogrebnyak Avatar asked Nov 18 '09 23:11

Alexander Pogrebnyak


People also ask

Are there print statements in SQL?

Usually, we use the SQL PRINT statement to print corresponding messages or track the variable values while query progress. We also use interactions or multiple loops in a query with a while or for a loop. We can also use the SQL PRINT statement to track the iteration.


2 Answers

Yes, there is: https://dba.stackexchange.com/a/44373/5457

Statement stmt = ...;
stmt.execute("some sql statement");
SQLWarning warning = stmt.getWarnings();

while (warning != null) {
    System.out.println(warning.getMessage());
    warning = warning.getNextWarning();
}
like image 64
Axel Fontaine Avatar answered Sep 28 '22 07:09

Axel Fontaine


this article shows how to do that in VB.NET

I am sure you can do the same in your java code.

All you need to do is attach a handler function to SqlInfoMessageEvent

VB.NET code specified in the above article does not work properly some how on my studio 2005 environment.

So I re wrote it as below

Imports System.Data.SqlClient
Module Module1

    Public Sub Main()

        'change your database name in following line.
        Dim conn As New SqlConnection("server=(local);Integrated Security=SSPI;database=Test")



        AddHandler conn.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)



        conn.Open()



        Dim cmd As New SqlCommand()

        cmd.Connection = conn

        cmd.CommandType = CommandType.StoredProcedure

        cmd.CommandText = "[SPWithPrint]"



        cmd.ExecuteNonQuery()



        conn.Close()



        ' Dts.TaskResult = Dts.Results.Success



    End Sub



    Private Sub OnInfoMessage(ByVal sender As Object, ByVal args As System.Data.SqlClient.SqlInfoMessageEventArgs)

        Dim err As SqlError
        For Each err In args.Errors
            Console.WriteLine("The {0} has received a severity {1}, state {2} error number {3}\n" & _
      "on line {4} of procedure {5} on server {6}:\n{7}", _
      err.Source, err.Class, err.State, err.Number, err.LineNumber, _
    err.Procedure, err.Server, err.Message)
        Next

    End Sub

End Module

Other usefull links are as below.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.infomessage.aspx

http://msdn.microsoft.com/en-us/library/a0hee08w.aspx

like image 36
N30 Avatar answered Sep 28 '22 08:09

N30