Access to SQL Server messages via ADO.NET

后端 未结 3 1700
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 10:59

Is it possible to access the SQL Server \"by-product messages\" via ADO.NET? Due to the lack of words, by \"by-product messages\" I mean the output which appears in the Mess

3条回答
  •  一个人的身影
    2020-12-10 11:13

    Based on marc_s' answer, I ve created a wrapper class

    public class SqlInfoMessageWrapper
    {
         public SqlInfoMessageWrapper(SqlConnection connection)
         {
                SqlConnection = connection;
                connection.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
          }
          public SqlConnection SqlConnection { get; set; }
          public string Message  { get; set; }
    
          void InfoMessageHandler(object sender, SqlInfoMessageEventArgs e)
          {
                Message = e.Message;
          }
     }
    

    Example of use :

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            var messageWrapper=new SqlInfoMessageWrapper(connection) ;
    
            var ret = SqlHelper2.ExecuteNonQuery(connection, CommandType.Text, command, null);
            messages+= $"{messageWrapper.Message} number of rows affected {ret} ";
        }
    

提交回复
热议问题