使用SqlDependency监测数据库
SqlDependency提供了:对监测的数据库发生变化通知前台程序的功能。
具体使用如下:
public Form1()
{
InitializeComponent();
SqlDependency.Start(conStr);
NewMethod();
}
string conStr = "data source=.;initial catalog=AssetsManageDB;uid=sa;pwd=****";
private void NewMethod()
{
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TT where flag=1",con);
SqlDependency dependy = new SqlDependency(cmd);
dependy.OnChange += new OnChangeEventHandler(dependy_OnChange);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show(dr["message"].ToString());
}
dr.Close();
}
}
void dependy_OnChange(object sender, SqlNotificationEventArgs e)
{
NewMethod();
}
Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=123;User ID=Admin;Data Source=123.mdb