使用SqlDependency监测数据库

本文介绍了如何使用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

转载于:https://www.cnblogs.com/Xingsoft-555/archive/2011/04/01/2002445.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值