C#使用sqldependency監聽SqlServer表數據的變化


sql server設置:ALTER DATABASE <DatabaseName> SET ENABLE_BROKER;語句讓相應的數據庫啟用監聽服務

當ALTER DATABASE Databasename SET ENABLE_BROKER; 執行過程中始終不能結束的時候。

 

ALTER DATABASE DatabaseName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE Databasename SET ENABLE_BROKER;
這樣可以執行完畢,以便支持SqlDependency特性。

先配置app.config

<connectionStrings >
<add name="SQLConnString" connectionString="Data Source=.;Initial Catalog=***;User ID=***;Password=***" providerName="System.Data.SqlClient"/>
</connectionStrings>

控制台程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

static void Main(string[] args)
{
_connStr = ConfigurationManager.ConnectionStrings["SQLConnString"].ToString();
SqlDependency.Start(_connStr);
UpdateGrid();
Console.ReadKey();

}

private static void UpdateGrid() {
using (SqlConnection con = new SqlConnection(_connStr)) {

using (SqlCommand cmd = new SqlCommand("select ID,UserID,[Message] From [dbo].[Messages]", con)) {
cmd.CommandType = CommandType.Text;
con.Open();
SqlDependency sqldep = new SqlDependency(cmd);
sqldep.OnChange += new OnChangeEventHandler(SqlDep_OnChange);
SqlDataReader sdr = cmd.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();
}

namespace Messge
{
class Program
{
private static string _connStr;
static void Main(string[] args)
{
_connStr = ConfigurationManager.ConnectionStrings["SQLConnString"].ToString();
SqlDependency.Start(_connStr);
UpdateGrid();
Console.ReadKey();

}

private static void UpdateGrid() {
using (SqlConnection con = new SqlConnection(_connStr)) {

using (SqlCommand cmd = new SqlCommand("select ID,UserID,[Message] From [dbo].[Messages]", con)) {
cmd.CommandType = CommandType.Text;
con.Open();
SqlDependency sqldep = new SqlDependency(cmd);
sqldep.OnChange += new OnChangeEventHandler(SqlDep_OnChange);
SqlDataReader sdr = cmd.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 SqlDep_OnChange(object sender,SqlNotificationEventArgs e) {

UpdateGrid();
}
}
}

效果:

數據庫變化前:

 

 

 

 數據庫變化后:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM