110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace SqlDependencyTest
{
class Program
{
private static string _connStr;
static void Main(string[] args)
{
_connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听
UpdateGrid();
Console.Read();
}
private static void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
using (SqlCommand command = new SqlCommand("select ID,UserID,[Message] From [dbo].[Messages]", connection))
{
command.CommandType = CommandType.Text;
connection.Open();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
SqlDataReader sdr = command.ExecuteReader();
Console.WriteLine();
while (sdr.Read())
{
Console.WriteLine("Id:{0}\tUserId:{1}\tMessage:{2}",sdr["ID"].ToString(), sdr["UserId"].ToString(),
sdr["Message"].ToString());
}
sdr.Close();
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
UpdateGrid();
}
}
}