• C# sqlserver监听数据表变化


     


    C# 监听数据库表的变化(SqlDependency)
    1
    class Program 2 { 3 static string connectionString = "Server=.;Database=testDemo;User Id=sa;Password=123456"; 4 static void Main(string[] args) 5 { 6 SqlDependency.Start(connectionString);//传入连接字符串,启动基于数据库的监听 7 UpdateGrid(); 8 Console.Read(); 9 SqlDependency.Stop(connectionString);//传入连接字符串,启动基于数据库的监听 10 } 11 private static void UpdateGrid() 12 { 13 using (SqlConnection connection = new SqlConnection(connectionString)) 14 { 15 connection.Open(); 16 //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[] 17 using (SqlCommand command = new SqlCommand("SELECT name,age FROM dbo.student", connection)) 18 { 19 command.CommandType = CommandType.Text; 20 //connection.Open(); 21 SqlDependency dependency = new SqlDependency(command); 22 dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); 23 using (SqlDataReader sdr = command.ExecuteReader()) 24 { 25 Console.WriteLine(); 26 while (sdr.Read()) 27 { 28 Console.WriteLine("AssyAcc:{0} Snum:{1} ", sdr["name"].ToString(), sdr["age"].ToString()); 29 } 30 sdr.Close(); 31 } 32 } 33 } 34 } 35 private static void dependency_OnChange(object sender, SqlNotificationEventArgs e) 36 { 37 if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据 38 { 39 UpdateGrid(); 40 } 41 } 42 }

     开启数据库Service Broker

    ALTER DATABASE testDemo SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
    ALTER DATABASE testDemo SET ENABLE_BROKER;

    转自:https://www.cnblogs.com/duhaoran/p/13047959.html
  • 相关阅读:
    Angular 组件通信的三种方式
    Vue 之keep-alive的使用,实现页面缓存
    Angular Service设计理念及使用
    Git提交规范
    angular的生命周期
    CPU 是如何认识和执行代码的
    Ubuntu 常用软件
    UltraSQL / sqlserver-kit (SQLServer DBA )高手
    便宜的网站模板下载
    Audio over Bluetooth: most detailed information about profiles, codecs, and devices
  • 原文地址:https://www.cnblogs.com/yeyuqian/p/13490674.html
Copyright © 2020-2023  润新知