如何在c#中设置SQL Server侦听器
本文关键字:SQL Server 侦听器 设置 | 更新日期: 2023-09-27 18:24:12
我一直在尝试从C#代码中找出如何在数据库表上设置侦听器。我最近一直在尝试设置SqlDependency
,但我被卡住了,因为我试图在其上应用该过程的数据库是只读的,我还没有权限更改它。
有人知道其他的方法来设置这样的东西吗?我的总体目标是允许我的应用程序侦听数据库,并在出现INSERT、UPDATE等时得到通知,并具体提供更改的内容(即哪一行)。
编辑:我无法访问插入/更新数据库的代码,我只能只读访问数据库本身。
您需要设置一个SqlDependency
并订阅OnChangeEventHandler
。请参阅learn.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);
}