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