我正在开发Windows软件,并且我有一个数据库。所以我想要的是,如果数据库记录已更新,我的Windows应用程序应自动检测它并检索那些更新的记录。有人可以为此提供解决方案吗?
答案 0 :(得分:0)
检查SqlDependency类
在Sql中:
ALTER DATABASE SampleDB SET SINGLE_USER;
ALTER DATABASE SampleDB SET ENABLE_BROKER;
ALTER DATABASE SampleDB SET MULTI_USER;
CREATE QUEUE myTableMessages;
CREATE SERVICE myTableNotifications ON QUEUE myTableMessages("http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification");
////
在视觉上:
using System;
using System.Data;
using System.Data.SqlClient;
namespace NotifyService
{
public class SqlNotifier : IDisposable
{
public SqlCommand SqlCmd { get; set; }
public SqlConnection SqlCon { get; set; }
public void StartMonitoring()
{
SqlDependency.Start(this.SqlCon.ConnectionString);
RegisterDependency();
}
private event EventHandler<SqlNotificationEventArgs> _NewNotification;
public event EventHandler<SqlNotificationEventArgs> NewNotification
{
add { this._NewNotification += value; }
remove { this._NewNotification -= value; }
}
public virtual void OnNewNotification(SqlNotificationEventArgs notification)
{
if (this._NewNotification != null)
this._NewNotification(this, notification);
}
public void RegisterDependency()
{
this.SqlCmd = new SqlCommand(SqlCmd.CommandText,this.SqlCon);
this.SqlCmd.Notification = null;
SqlDependency dependency = new SqlDependency(this.SqlCmd);
dependency.OnChange += this.Dependency_OnChange;
if (this.SqlCon.State == ConnectionState.Closed)
this.SqlCon.Open();
this.SqlCmd.ExecuteReader();
this.SqlCon.Close();
}
private void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= new OnChangeEventHandler(Dependency_OnChange);
this.OnNewNotification(e);
RegisterDependency();
}
public void Dispose()
{
SqlDependency.Stop(this.SqlCon.ConnectionString);
}
}
}
/// 使用:
using NotifyService;
private SqlNotifier NS = new SqlNotifier();
NS.SqlCon = new SqlConnection(@"Data Source=127.0.0.1;Initial Catalog=SampleDB;Persist Security Info=True;User ID=sa;Password=***");
NS.SqlCmd = new SqlCommand("SELECT id, name FROM dbo.mytable");
NS.StartMonitoring();
NS.NewNotification += new EventHandler<SqlNotificationEventArgs>(DependencyEventHandler);