【问题标题】:How to set up SQL Server listener in c#如何在 C# 中设置 SQL Server 侦听器
【发布时间】:2015-11-23 23:57:03
【问题描述】:

我一直在尝试从我的 C# 代码中找出如何在数据库表上设置侦听器。我最近一直在尝试设置SqlDependency,但我被卡住了,因为我尝试应用该过程的数据库是只读的,我没有更改它的权限(还)。

有没有人知道其他方法来设置这样的东西?我的总体目标是允许我的应用程序侦听数据库并在有 INSERT、UPDATE 等时收到通知,并具体提供更改的内容(即哪一行)。

编辑:我无权访问插入/更新数据库的代码,我拥有的只是对数据库本身的只读访问权限。

【问题讨论】:

  • 你不能从插入数据库的代码中跟踪它吗?
  • 啊,不.. 我有一个非常奇怪的情况,我无法访问那部分代码(会很好,对吧?)我可以访问的所有内容都是读取-只有插入到的数据库的权限..
  • 什么是延迟要求?您是否需要立即知道,或者您只是想捕获详细的更改历史以了解正在发生的事情。将更改触发器插入到随后与外部进程通信的表中可能会导致数据库操作出现问题。最好的方法可能是只为表打开 CDC,然后以最小的影响跟踪每个更改,然后您可以对其进行询问。你能发布确切版本的 SQL Server 吗?
  • 阅读SQlDependency,这似乎可以满足您的需求,但请注意性能影响。如果一个批次突然有 10 万个变化,会发生什么?

标签: c# asp.net .net sql-server


【解决方案1】:

您需要设置SqlDependency 并订阅OnChangeEventHandler。见example from docs.microsoft.com

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

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

    // Create a new SqlCommand object.
    using (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 reference 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);
}

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 2011-08-16
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多