C # sqlserver data change automatic start program SqlDependency

I am a java developer. The task is coming, only on the stubborn head. The most recent task is that the company has bought a new Kingdee ERP. My previous work has been completed. Now I need to do extra functions for this ERP. The first function is When the data of a field in a database changes, start the program to change the specified table, and the following code is directly added:

Function: SqlDependency provides a mechanism. When the data in the monitored database changes, SqlDependency will automatically trigger the OnChange event to notify the application, so that the application can update the data (or cache) in real time without having to periodically Request backend, if you add SignalR technology, you can basically achieve real-time communication.

1.SQL SERVER do effective setting for SqlDependency.

    Enable SQL Server Service Broker for the current database

    a. Check if Service Broker is enabled

  

SELECT is_broker_enabled FROM sys.databases WHERE name = 'WLZhuJianMes' 

//查询结果:is_broker_enabled de 结果是  0,代表数据库没有启动 Service Broker

//解决办法:注:两句同时执行,单独执行显示:正在回滚不合法事务。估计回滚已完成: 100%。

b Open  Service Broker



ALTER DATABASE WLZhuJianMes SET NEW_BROKER WITH ROLLBACK IMMEDIATE; 

ALTER DATABASE WLZhuJianMes  SET ENABLE_BROKER; 



//再次查询is_broker_enabled状态,状态为1,数据库没有启动 Service Broker成功
光用ALTER DATABASE DBName SET ENABLE_BROKER;语句开启经常会死机卡住,解决这个问题的方法是,先停止其它正在使用数据库的程序,然后运行
//ALTER DATABASE DBName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
//ALTER DATABASE DBName SET ENABLE_BROKER;
在数据库中停用 Service Broker
将数据库改为设置 DISABLE_BROKER 选项。
示例


复制
USE master ;
GO

ALTER DATABASE AdventureWorks2008R2 SET DISABLE_BROKER ;
GO

2. Download VS, a lot of this site online, download SQLSERVER.

 

3. New windows service program in VS, the code is as follows

   You need to monitor which table and which field need to be written, and write multiple code blocks for multiple tables.

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace SqlDependencyTest
{
    class Program
    {
        private static string _connStr = "server=.;database=homey;uid=sa;pwd=FL33771";

        static void Main(string[] args)
        { 
            SqlDependency.Start(_connStr);
            UpdateGrid();
            Console.Read();
        }
         

        private static void UpdateGrid()
        {
            using (SqlConnection connection = new SqlConnection(_connStr))
            {
                using (SqlCommand command = new SqlCommand("select ID,UserID,[Message] From [dbo].[Messages]", 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}\tUserId:{1}\tMessage:{2}", sdr["ID"].ToString(), sdr["UserId"].ToString(),
                        sdr["Message"].ToString());
                    }
                    sdr.Close();
                }
            }
        }


        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            UpdateGrid();
        }
    }
}

At this point, my client has been able to monitor the data changes of the local SQLSERVER, and make corresponding actions that are displayed. Here you can play the actions after the monitoring is in place.

 

 

Published 51 original articles · Like 4 · Visitors 7880

Guess you like

Origin blog.csdn.net/u012174809/article/details/103819238