使用SqlDependency監測資料庫

kingwebo'sZone發表於2020-12-09
  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();
        }

 

開啟方式:

USE DB_MyDB
GO
ALTER DATABASE DB_MyDB SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE DB_MyDB SET ENABLE_BROKER;

相關文章