如何在 C# 中监视对我的数据库表的更改?我正在使用 SQL Server 2008,并且我想在更改表时同步数据。
问问题
3553 次
2 回答
3
如果我理解正确,您想创建一个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);
}
于 2012-05-03T09:31:57.310 回答
2
于 2012-11-17T11:20:01.737 回答