2017-09-16 53 views
0

請遵守下面的示例C#代碼:如何在ADO.NET中的SELECT語句之後捕獲PRINT事件?

using System; 
using System.Data.SqlClient; 

namespace MyApp 
{ 
    internal class Program 
    { 
     private const string SQL = "SELECT 10;PRINT 'OK'"; 

     private static void Main(string[] args) 
     { 
      using (var c = new SqlConnection("server=localhost;trusted_connection=yes")) 
      { 
       c.Open(); 
       c.InfoMessage += OnInfoMessage; 
       c.Disposed += OnConnDisposed; 

       Console.WriteLine("--- Select ---"); 
       Select(c, SQL); 

       Console.WriteLine("--- Execute ---"); 
       Execute(c, SQL); 

       Console.WriteLine("--- ExecuteScalar ---"); 
       ExecuteScalar(c, SQL); 
      } 
     } 

     private static void Execute(SqlConnection c, string sql) 
     { 
      using (var cmd = c.CreateCommand()) 
      { 
       cmd.CommandText = sql; 
       cmd.ExecuteNonQuery(); 
      } 
     } 

     private static void ExecuteScalar(SqlConnection c, string sql) 
     { 
      using (var cmd = c.CreateCommand()) 
      { 
       cmd.CommandText = sql; 
       Console.WriteLine(cmd.ExecuteScalar()); 
      } 
     } 

     private static void Select(SqlConnection c, string sql) 
     { 
      using (var cmd = c.CreateCommand()) 
      { 
       cmd.CommandText = sql; 
       using (var reader = cmd.ExecuteReader()) 
       { 
        reader.Read(); 
        Console.WriteLine(reader.GetInt32(0)); 
       } 
      } 
     } 

     private static void OnConnDisposed(object sender, EventArgs e) 
     { 
      var sqlConnection = (SqlConnection)sender; 
      sqlConnection.InfoMessage -= OnInfoMessage; 
      sqlConnection.Disposed -= OnConnDisposed; 
     } 

     private static void OnInfoMessage(object sender, SqlInfoMessageEventArgs args) 
     { 
      Console.WriteLine("PRINT"); 
     } 
    } 
} 

運行它產生以下輸出:

--- Select --- 
10 
--- Execute --- 
PRINT 
--- ExecuteScalar --- 
10 

正如你所看到的,既不Select也不ExecuteScalar捕獲跟隨SELECT 10聲明PRINT事件。

我怎樣才能引起Select(我不關心ExecuteScalar,它是爲了完整性的緣故)都得到結果集並導致打印事件,像它的Execute方法?

回答

0

當你傳遞一個批處理(多個語句)時,你必須循環訪問結果集,當你使用Execute命令時。

private static void Select(SqlConnection c, string sql) 
{ 
    using (var cmd = c.CreateCommand()) 
    { 
     cmd.CommandText = sql; 
     using (var reader = cmd.ExecuteReader()) 
     { 
      do 
      { 
       if (reader.Read()) 
        Console.WriteLine(reader.GetInt32(0)); 
      } 
      while (reader.NextResult()); 
     } 
    } 
} 

ExecuteScalar將從第一個結果集的第一行返回第一個值。

+0

愚蠢的我,我從來沒有意識到我不得不調用'reader.NextResult()'。該調用返回'false',因爲沒有下一個結果,但通過調用它,我導致捕獲PRINT事件。 – mark