Use SqlDependency to listen to SQL Server database changes and execute events in real time

Source: Internet
Author: User

SQL Server settings:ALTER database <DatabaseName> set Enable_broker; statement enables the appropriate database to enable the Listener service in order to support the SqlDependency feature

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Windows.Forms;

Namespace WindowsFormsApplication1
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}

private static String conn = "database connection statement";
static SqlDependency dependency;

private void Form1_Load (object sender, EventArgs e)
{
String sql = "Select u_ipaddress from Wps_user_m";
DataTable dt = sqlhelper.query (SQL). Tables[0];
Datagridview1.datasource = DT;

Start and Stop methods
Sqldependency.start (conn);
Update (conn);
}

private static void Update (String conn)
{
using (
SqlConnection connection =
New SqlConnection (conn))
{
It is important to note that you cannot use the * table name to add [dbo] Otherwise it will appear that the execution OnChange is always called
String sql = "Select u_ipaddress from dbo. Wps_user_m ";

using (SqlCommand command = new SqlCommand (SQL, connection))
{
Connection. Open ();
Command.commandtype = CommandType.Text;
Dependency = new SqlDependency (command);
Dependency. OnChange + = new Onchangeeventhandler (dependency_onchange);
command must be executed.
Command. ExecuteNonQuery ();
Console.WriteLine (dependency. HasChanges);
}
}
}
private static void Dependency_onchange (object sender, Sqlnotificationeventargs e)
{
Console.WriteLine ("OnChange Method:" + dependency. HasChanges);
Console.WriteLine ("Database data Changed" + DateTime.Now);
Here to call again
Update (conn);
}
}
}

Use SqlDependency to listen to SQL Server database changes and execute events in real time

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.