【问题标题】:Detect SQL database changes检测 SQL 数据库更改
【发布时间】:2014-10-29 11:34:13
【问题描述】:

考虑这个例子:

INSERT INTO [Table] (column1)
SELECT value1

如果我要在 SSMS 中执行此命令,对于 c# 表单应用程序,我需要做什么才能识别此事件?就像应用程序在此事件发生时显示 MessageBox 一样简单。我似乎无法解决这个问题或找到任何有用的数据。我曾尝试使用SqlDependency,但没有任何运气。如果那是我需要走的路,谁能帮助我更好地理解这个概念?

【问题讨论】:

  • 如果我理解你,你想在你的 sql server 运行插入选择时在你的 c# 应用程序中触发一个事件?
  • @paqogomez 正确!有点像 ssms 中的触发器,我想要 C# 中的触发器
  • 您想检测来自 C# 应用程序的数据库何时发生变化? SQL Server 不推送通知,因此您将不得不轮询某些内容。您可以做的一件事是在需要将日志记录到审计表的地方添加INSERT TRIGGER,并从那里添加SELECT
  • SQL Server 支持编写基于 CLR 的触发器。这意味着您可以在插入某些内容时运行 C# 代码。我建议您使用它并让触发器以某种方式向应用程序发送事件。
  • 什么时候改变(更新)或者什么时候插入?当您尝试 SQLDependency 时发生了什么?

标签: c# sql listener service-broker sqldependency


【解决方案1】:

如果您想检测更改而不仅仅是插入,您可以使用SQL Dependency 实现此目的。您是否阅读并尝试过链接中的示例?

Heres a nice 'tutorial / example' that works and runs you through the basics.

Heres a nice overview of Query Notifications.

  • 底层实现由暴露服务器端功能的 SqlNotificationRequest 类提供,使您能够执行带有通知请求的命令。

  • 高级实现由 SqlDependency 类提供,该类提供源应用程序和 SQL Server 之间通知功能的高级抽象,使您能够使用依赖项来检测更改服务器。在大多数情况下,这是通过托管客户端应用程序使用 SQL Server 的 .NET Framework 数据提供程序来利用 SQL Server 通知功能的最简单、最有效的方法。

  • 此外,使用 ASP.NET 2.0 或更高版本构建的 Web 应用程序可以使用 SqlCacheDependency 帮助器类。

它与“SqlDependency 对象可以与 SqlCommand 关联以检测查询结果何时与最初检索的结果不同”一样基本。

您必须先Enable Query Notifications 并关注Creating a Query for Notification

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

void SomeMethod()
{
    // Assume connection is an open SqlConnection.
    // Create a new SqlCommand object which directly references (no synonyms) the data you want to check for changes.
    using (SqlCommand command=new SqlCommand("SELECT value1 FROM [Table]", 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.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 2012-01-27
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
相关资源
最近更新 更多