我使用Detecting Changes with SqlDependency作为我正在编写的代码的示例。我也看过其他类似代码的链接,但都没有。
基本上,我只是想在对表label1.Text
进行更改时更改[ErrorLog]
。出于某种原因,OnDependencyChange
没有被解雇。
我在数据库中启用了Service Broker
:
ALTER DATABASE TestDB
SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
现在,这是我的完整代码。这很短:
public partial class Form1 : Form
{
private string GetConnectionString()
{
return @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=TestDB;Persist Security Info=True;User ID=TestUser;Password=12345;";
}
SqlConnection connection;
public Form1()
{
InitializeComponent();
connection = new SqlConnection(GetConnectionString());
connection.Open();
SqlDependency.Start(GetConnectionString());
i = 0;
}
int i;
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
i++;
label1.Text = "Changed: " + i.ToString();
// Handle the event (for example, invalidate this cache entry).
}
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
using (SqlCommand command =
new SqlCommand("SELECT [ErrorLog].[ID],[ErrorLog].[Project],[ErrorLog].[Form],[ErrorLog].[Message],[ErrorLog].[Exception],[ErrorLog].[InsertDate] " +
"FROM [dbo].[ErrorLog]", 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.
}
}
}
}
我检查了服务代理是否已启用且是;以下返回1:
SELECT is_broker_enabled
FROM sys.databases
WHERE name = 'TestDB';
感谢任何帮助。
感谢。
答案 0 :(得分:2)
除了一件事,你正在做的一切正确。在SomeMethod()
构造函数中调用方法Form1
。
对表格数据的所有后续更改都会触发相关性更改。