Monday, July 28, 2025

How to print a print statement of sql in asp.net c# - how to call a another event in asp.net event

 using System;

using System.Data.SqlClient;


public class SqlPrintExample

{

    public static void Main(string[] args)

    {

        string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";

        string sqlQuery = "PRINT 'This message comes from SQL.'; SELECT GETDATE() AS CurrentDateTime;";


        using (SqlConnection connection = new SqlConnection(connectionString))

        {

            // Attach an event handler to capture InfoMessage events (including PRINT statements)

            connection.InfoMessage += Connection_InfoMessage;

or// conn.InfoMessage += new SqlInfoMessageEventHandler( Connection_InfoMessage);

            try

            {

                connection.Open();

                using (SqlCommand command = new SqlCommand(sqlQuery, connection))

                {

                    using (SqlDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            Console.WriteLine($"Current Date Time from SQL: {reader["CurrentDateTime"]}");

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Error: {ex.Message}");

            }

        }

    }


    private static void Connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)

    {

        // Display the message from the SQL PRINT statement

        Console.WriteLine($"SQL InfoMessage: {e.Message}");

    }

}

No comments:

Post a Comment