且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.Net SQL Server数据库监视 - 插入,更新,删除

更新时间:2023-02-08 17:21:03

要监视SQL表或记录在SQL 2005+中的更改,您可以使用SqlDependency类。

To monitor for changes to a SQL table or record in SQL 2005+ you can utilize the SqlDependency class.

针对在ASP.NET或中间层服务中使用,其中单个服务器正在针对数据库管理活动预订 - 而不是数百个客户端管理预订。根据您引用的最大客户端数量,您可能希望构建一个缓存池服务,可以根据您的客户端管理SQL的通知订阅。

It is targeted for use in ASP.NET or a middle-tier service where a single server is managing active subscriptions against a database - not multiple hundreds of clients managing subscriptions. Depending on the maximum number of clients you are referring to you may want to build a cache pooling service that can manage the notification subscriptions against SQL to your clients.

内部使用SqlNotificationRequest,它使用Service Broker,而不是Notification Services。因此,这应该在SQL 2008等工作。

Inside it uses SqlNotificationRequest which uses Service Broker, not Notification Services. Thus, this should work going forward on SQL 2008, etc.

MSDN for SqlDependency

void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
  // Assume connection is an open SqlConnection.

  // Create a new SqlCommand object.
  SqlCommand command=new SqlCommand(
    "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", 
    connection);

  // Create a dependency and associate it with the SqlCommand.
  SqlDependency dependency=new SqlDependency(command);
  // Maintain the refence in a class member.

  // Subscribe to the SqlDependency event.
  dependency.OnChange+=new OnChangeEventHandler(OnDependencyChange);

  // Execute the command.
  command.ExecuteReader();
  // Process the DataReader.
}

// Handler method
void OnDependencyChange(object sender, 
   SqlNotificationsEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

使用和监控SQL 2005查询通知在您的代码(使用Web应用程序作为示例)中设置它以及订阅Service Broker等所需的适当的SQL权限。

"Using and Monitoring SQL 2005 Query Notifications" article that talks you through the steps to set it up in your code (using a web app as example) along with the appropriate SQL permissions that are required to subscribe to Service Broker and so on.

a href =http://msdn.microsoft.com/en-us/library/system.web.caching.sqlcachedependency.aspx =noreferrer> ASP.NET(网络缓存)类也是可用于Web方案。

An ASP.NET (web caching) class is also available for web scenarios.