如何保持 sql 依赖项发挥其作用

编程入门 行业动态 更新时间:2024-10-11 17:19:21
本文介绍了如何保持 sql 依赖项发挥其作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序.

I have a console application.

我想继续观察我的数据库表中特定列的变化.

I wanna keep watching the changes on a specific column in my database table.

我通过互联网阅读,发现 sql 依赖对我的目的有好处.我开始了解它并做了以下事情:

I read through internet and I have found that sql dependency is good for my purpose. I started learning about it and I did the following:

创建一个类.在构造函数中,我调用了静态函数start,并调用了一个具有所有sql依赖设置的函数. create a class. In the constructor, I called the static function start and I called a function that has all the sql dependency settings.

我的问题

当我使用 start 点击 Visual Studio 2013 运行应用程序时,应用程序运行然后停止.但是,我需要的是应用程序开始工作并持续关注我的数据库表中的更改.

My problem

When I run the application using the start click on visual studio 2013, the apps works and then stops. However, what I need is that the apps starts working and keep watching for changes in my database's table.

你能帮帮我吗?

这是一个非常非常简单的c#代码.

This is a very very simple c# code.

public class MyListener
    {
        public MyListener()
        {
            SqlDependency.Start(getConnectionString());
            this.listen();
        }

        private string getConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["popup"].ConnectionString.ToString();
        }
        private void listen()
        {
            string query = "SELECT CallerID FROM TransferToSIP WHERE hasBeenRead = 0";
            SqlConnection con = new SqlConnection(getConnectionString());
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            using (cmd)
            {
                SqlDependency dependency = new SqlDependency(cmd);
                dependency.OnChange += new
                   OnChangeEventHandler(OnDependencyChange);
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                }
            }
        }
        void OnDependencyChange(object sender, SqlNotificationEventArgs e)
        {
            Console.WriteLine("Roma");
        }
        void Termination()
        {
            SqlDependency.Stop(getConnectionString());
            Console.Read();
        }

推荐答案

问题在于没有重新订阅.您应该在 OnDependencyChange 中调用 listen 方法.我知道这很奇怪,但它是 SqlDependency 类.

The problem is in absence of the resubscruption. You should call the listen method inside of OnDependencyChange. I know that it is weird, but it is the SqlDependency class.

这篇关于如何保持 sql 依赖项发挥其作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-19 00:25:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:作用   sql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!