使用SqlDependency實時監聽SQL server數據庫變化並執行事件

sql server設置:ALTER DATABASE <DatabaseName> SET ENABLE_BROKER;語句讓相應的數據庫啓用監聽服務,以便支持SqlDependency特性sql

 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private static string conn = "數據庫鏈接語句";
        static SqlDependency dependency;
        private void Form1_Load(object sender, EventArgs e)
        {
            //string sql = "SELECT u_ipaddress FROM WPS_User_M";
            //DataTable dt = SqlHelper.Query(sql).Tables[0];
            //dataGridView1.DataSource = dt;

            //Start和Stop方法
            SqlDependency.Start(conn);
            Update(conn);
        }

        private static void Update(string conn)
        {
            using (
            SqlConnection connection =
            new SqlConnection(conn))
            {
                //此處 要注意 不能使用* 表名要加[dbo] 不然會出現一直調用執行 OnChange
                string sql = "SELECT u_ipaddress FROM dbo.WPS_User_M";

                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();
                    command.CommandType = CommandType.Text;
                    dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    //必需要執行一下command
                    command.ExecuteNonQuery();
                    Console.WriteLine(dependency.HasChanges);
                }
            }
        }
        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            Console.WriteLine("onchange方法中:" + dependency.HasChanges);
            Console.WriteLine("數據庫數據發生變化" + DateTime.Now);
            //這裏要再次調用
            Update(conn);
        }
    }
}
相關文章
相關標籤/搜索