Skip to main content
 首页 » 编程设计

c#之如何使用 SqlDependency 监控 2 或 3 表数据更改

2024年02月06日12zhwl

这样我们通过sql依赖监控表数据变化。

private static void RegisterNotification() 
        { 
            try 
            { 
                using (SqlConnection conn = new SqlConnection(connectionString)) 
                { 
                    conn.Open(); 
                    SqlCommand cmd = conn.CreateCommand(); 
                    cmd.CommandText = "SELECT ID, Name FROM dbo.TestTable"; 
                    dep = new SqlDependency(cmd); 
                    dep.OnChange += new OnChangeEventHandler(OnDataChange); 
                    SqlDataReader dr = cmd.ExecuteReader(); 
                    { 
                        while (dr.Read()) 
                        { 
                            Console.WriteLine("Name = " + dr[1].ToString()); 
                        } 
                    } 
                    dr.Close(); 
                    Console.WriteLine("Waiting for any data changes...\nPress to end program."); 
                    Console.ReadLine(); 
                } 
            } 
            finally 
            { 
                //SqlDependency.Stop(connStr); 
            } 
 
        } 

通过这种方式,我们指定 sql SELECT ID, Name FROM dbo.TestTable 进行表更改。我想知道我是否需要监控 2 个表然后我们可以这样写 sql

SELECT ID, Name FROM dbo.TestTable1;SELECT ID, Name FROM dbo.TestTable2 

然后像这样读取表格数据

SqlDataReader dr = cmd.ExecuteReader(); 
{ 
     while (dr.Read()) 
     { 
        Console.WriteLine("Name = " + dr[1].ToString()); 
     } 
 } 

然后再次 dr.NextResult() 并再次阅读

 while (dr.Read()) 
         { 
            Console.WriteLine("Name = " + dr[1].ToString()); 
         } 

如果我要错误地监控多个表数据的变化,那么请用正确的信息指导我。寻找建议。谢谢

请您参考如下方法:

这里有源代码的非常好的文章

SQL 缓存与 SQL Server、LINQ 和 ASP.NET 3.5 的依赖关系 http://www.dotnetcurry.com/showarticle.aspx?ID=263

重要(来自文章)

GRANT SUBSCRIBE QUERY NOTIFICATIONS TO "TESTSERVER\ASPNET" 

C#

protected void Application_Start(object sender, EventArgs e) 
{ 
SqlDependency.Start(ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString); 
} 

以下代码也会停止监听器:

protected void Application_End(object sender, EventArgs e) 
{ 
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString); 
}