【问题标题】:Detect SQL event with C# application使用 C# 应用程序检测 SQL 事件
【发布时间】:2014-10-29 04:38:39
【问题描述】:

我有下面的代码(为了清楚起见,来自 MSDN 网站的文字复制/粘贴),它似乎可以正常连接(除了“拒绝访问”错误,这没关系,因为我的安全请求还没有消失通过了)。我需要做的是检测我们的 sql 服务器何时执行了insertupdate 操作。基本上,这个应用程序应该 24/7 全天候运行,并在这样的操作遇到侦听器时执行某些功能。我不是要求将代码摆在我面前,而是要求从哪里开始。这是我目前不知道该怎么做的事情,并且被告知我大约有一周的时间来弄清楚并完成它。有人可以指出我正确的方向吗?提前谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Connect_Server
{
    class Program
    {
        static string output = "";

        static void Main(string[] args)
        {
            createListener();
        }

        static public void createListener()
        {
            // Create an instance of the TcpListener class.
            TcpListener tcpListener = null;
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            try
            {
                // Set the listener on the local IP address 
                // and specify the port.
                tcpListener = new TcpListener(ipAddress, 80);
                tcpListener.Start();
                output = "Waiting for a connection...";
            }
            catch (Exception e)
            {
                output = "Error: " + e.ToString();
                Console.Write(output);
            }
            while (true)
            {
                // Always use a Sleep call in a while(true) loop 
                // to avoid locking up your CPU.
                Thread.Sleep(10);
                // Create a TCP socket. 
                // If you ran this server on the desktop, you could use 
                // Socket socket = tcpListener.AcceptSocket() 
                // for greater flexibility.
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                // Read the data stream from the client. 
                byte[] bytes = new byte[256];
                NetworkStream stream = tcpClient.GetStream();
                stream.Read(bytes, 0, bytes.Length);
                SocketHelper helper = new SocketHelper();
                helper.processMsg(tcpClient, stream, bytes);
            }
        }

    }
}

【问题讨论】:

  • 你检查过SqlDependency吗??
  • @apomene 根据 MSDN “可以将 SqlDependency 对象与 SqlCommand 关联,以便检测查询结果何时与最初检索的结果不同。”我不相信这是我需要做的,但可能是错误的。我需要知道 OUTSIDE 应用程序何时修改数据库。它不会在我正在编写的应用程序中修改。
  • 外源将数据发送到db,我的程序需要检测数据发送,做操作,然后更新发送的数据。

标签: c# sql events tcp listener


【解决方案1】:

查看SQL Server Notifications。当某些基础数据集发生更改时,这将向您的应用程序发送信号。我不确定这对服务器来说有多重,所以如果您有大量客户端等待通知,您应该仔细对其进行负载测试....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 2018-03-19
    相关资源
    最近更新 更多