监听数据库变化 .net实现

 

监听数据库是否发生变化,运用Service Broker、SqlDependency,在.net下实现如下:

        private bool flag = false;

        private void button1_Click(object sender, EventArgs e)
        {
            string str = "Data Source=DATASERVER;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa";
            using( SqlConnection conn = new SqlConnection(str))
            using (SqlCommand cmd = new SqlCommand("select * from TableOperate", conn))
            {
                SqlDependency.Start(str);
                SqlDependency depend = new SqlDependency(cmd);
                depend.OnChange += new OnChangeEventHandler(depend_OnChange);
               
                conn.Open();
                if (flag)
                {
                    cmd.ExecuteNonQuery();
                    flag = false;
                }
                else
                {
                    MessageBox.Show("未监听数据库更改....");
                    flag = true;
                }
            }
        }

        private void depend_OnChange(object sender, SqlNotificationEventArgs e)
        {
            MessageBox.Show("已监听到数据库更改了.....");
        }

你可能感兴趣的:(数据库,.net,object,security,cmd,button)