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