首先要启用Service Broker
ALTER DATABASE 数据库名称 SET NEW_BROKER WITH ROLLBACK IMMEDIATE; ALTER DATABASE 数据库名称 SET ENABLE_BROKER;
然后sql语句必须是依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
static void Main(string[] args) { SqlDependency.Start(connectionString);//传入连接字符串,启动基于数据库的监听 UpdateGrid(); Console.Read(); SqlDependency.Stop(connectionString); } static string connectionString = "Server=ADMIN-PC;Database=newsData;User Id=sa;Password=123456"; private static void UpdateGrid() { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT id,cemskind FROM [dbo].[op_weight_cemskind]", connection)) { command.CommandType = CommandType.Text; SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); using (SqlDataReader sdr = command.ExecuteReader()) { Console.WriteLine(); while (sdr.Read()) { Console.WriteLine("ID:{0}\t数据:{1}\t", sdr["id"].ToString(), sdr["cemskind"].ToString()); } sdr.Close(); } } } } private static void dependency_OnChange(object sender, SqlNotificationEventArgs e) { if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据 { UpdateGrid(); } }
监听结果