ADO.NET 2.0中的查询通知
http://tech.ddvip.com 2008年01月22日 社区交流
内容摘要:学习如何使用ADO.NET 2.0和SQL Server 2005中新的通知技术处理即席数据刷新。
using System;
using System.Data;
using System.Data.SqlClient;
static void Main(string[] args)
{
string connstring = GetConnectionStringFromConfig();
using (SqlConnection conn = new SqlConnection(connstring))
using (SqlCommand cmd =
// 2-part table names, no "SELECT * FROM ..."
new SqlCommand("SELECT au_id, au_lname FROM dbo.authors", conn))
{
try
{
// create dependency associated with cmd
SqlDependency depend = new SqlDependency(cmd);
// register handler
depend.OnChanged += new OnChangedEventHandler(MyOnChanged);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
// process DataReader
while (rdr.Read())
Console.WriteLine(rdr[0]);
rdr.Close();
// Wait for invalidation to come through
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
catch (Exception e)
{ Console.WriteLine(e.Message); }
}
}
static void MyOnChanged(object caller, SqlNotificationEventArgs e)
{
Console.WriteLine("result has changed");
Console.WriteLine("Source " + e.Source);
Console.WriteLine("Type " + e.Type);
Console.WriteLine("Info " + e.Info);
}
同样的代码您也可以使用Visual Basic .NET编写,使用熟悉的WithEvents关键字和SqlDependency. 注意这段程序只接收和处理一个OnChanged事件,而不管底层行集发生了多少次改变。收到通知时我们要做的工作就是重新提交附带新的通知请求的命令,并使用该命令的执行结果刷新缓存以反映出新数据。如果将上面例子中Main() 的代码转移到一个命名的例程中,代码看起来应如下所示:
来源:51CTO 责编:豆豆技术应用