C# 实时监控数据库SqlDependency

http://blog.csdn.net/idays021/article/details/49661855

 class Program
    {
        private static string _connStr; 


        static void Main(string[] args)
        {
            _connStr = ConfigurationManager.ConnectionStrings["plmConnectionString"].ToString();
            SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听  
            UpdateGrid();


            Console.Read();
        }


        private static void UpdateGrid()
        {
            using (SqlConnection connection = new SqlConnection(_connStr))
            {
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[],如果where条件存在datetime类型,就会导致一直触发onChange事件  
                using (SqlCommand command = new SqlCommand("select id,machine,jobNo From [dbo].[plm_Issue]", connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);


                    SqlDataReader sdr = command.ExecuteReader();
                    Console.WriteLine();
                    while (sdr.Read())
                    {
                        Console.WriteLine("id:{0}\t machine:{1}\t jobNo:{2}", sdr["id"].ToString(), sdr["machine"].ToString(),


 sdr["jobNo"].ToString());
                    }
                    sdr.Close();
                }
            }
        }




        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            SqlDependency dependency = sender as SqlDependency;
            dependency.OnChange -= dependency_OnChange;
            if (e.Info != SqlNotificationInfo.Invalid)
            {
                UpdateGrid();//此处需重复注册<span style="font-family: Arial, Helvetica, sans-serif;">SqlDependency,每次注册只执行一次,SqlDependency.id可用用于验证注册唯一 编号  
            }
        }  
    }


在数据库执行如下sql 语句

  1. ALTER DATABASE 数据库名称 SET NEW_BROKER WITH ROLLBACK IMMEDIATE;  
  2. ALTER DATABASE 数据库名称 SET ENABLE_BROKER;  

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是使用C#代码监听SQL Server数据库的示例: ```csharp using System; using System.Data.SqlClient; class Program { static void Main() { string connectionString = "Data Source=(local);Initial Catalog=YourDatabase;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlDependency.Start(connectionString); Console.WriteLine("Listening to database changes..."); using (SqlCommand command = new SqlCommand("SELECT * FROM YourTable", connection)) { SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(OnNotificationChange); // Start the command execution using (SqlDataReader reader = command.ExecuteReader()) { // Process the data } } } } private static void OnNotificationChange(object sender, SqlNotificationEventArgs e) { Console.WriteLine("Database changed!"); // Handle the database change event } } ``` 在上面的示例中,我们创建一个 `SqlConnection` 实例并使用 `SqlDependency.Start()` 方法启动侦听器。然后,我们创建一个 `SqlCommand` 实例并将其传递给 `SqlDependency` 构造函数,然后订阅 `SqlDependency.OnChange` 事件,该事件将在数据库更改时触发。在事件处理程序中,您可以处理数据库更改事件。 请注意,为了使侦听器正常工作,需要进行以下配置: 1. SQL Server 服务必须启用 Service Broker。 2. 数据库必须启用 Service Broker 并启用对该数据库的通知。 3. 授予使用数据库的用户 RECEIVE 权限。 希望能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值