C#_SqlDependency的使用詳解
C#_SqlDependency的使用
SqlDependency允許你在數(shù)據(jù)庫中的原始數(shù)據(jù)更改時接收通知,要接收通知,您需要訂閱OnChange事件。
SqlDependency有如下限制:
- SELECT語句中的投影列必須明確聲明,并且表名必須由兩部分組成。請注意,這意味著該語句中引用的所有表必須位于同一數(shù)據(jù)庫中。
- 該語句不能使用星號(*)或table_name。*語法指定列。
- 該語句不能使用未命名的列或重復的列名。
- 該語句必須引用基表。
- 該語句不能引用具有計算列的表。
- 除非該語句使用GROUP BY表達式,否則SELECT語句中的投影列可能不包含聚合表達式。提供GROUP BY表達式時,選擇列表可能包含聚合函數(shù)COUNT_BIG()或SUM()。但是,不能為可為空的列指定SUM()。該語句可能未指定HAVING,CUBE或ROLLUP。
- SELECT語句中用作簡單表達式的投影列不得出現(xiàn)多次。
- 該聲明不能包含PIVOT或UNPIVOT運算符。
- 該語句不能包含UNION,INTERSECT或EXCEPT運算符。
- 該語句不能引用視圖。
- 該語句不得包含以下任何內(nèi)容:DISTINCT,COMPUTE或COMPUTE BY或INTO。
- 該語句不能引用服務器全局變量(@@ variable_name)。
- 該語句不能引用派生表,臨時表或表變量。
- 該語句不得引用其他數(shù)據(jù)庫或服務器中的表或視圖。
- 該語句不能包含子查詢,外部聯(lián)接或自我聯(lián)接。
- 該語句不能引用大型對象類型:text,ntext和image。
- 該語句不得使用CONTAINS或FREETEXT全文謂詞。
- 該語句不得使用行集函數(shù),包括OPENROWSET和OPENQUERY。
- 該語句不得使用以下任何聚合函數(shù):AVG,COUNT(*),MAX,MIN,STDEV,STDEVP,VAR或VARP。
- 該語句不得使用任何不確定的函數(shù),包括排名和窗口函數(shù)。
- 該語句不能包含用戶定義的聚合。
- 該語句不得引用系統(tǒng)表或視圖,包括目錄視圖和動態(tài)管理視圖。
- 該語句不能包含F(xiàn)OR BROWSE信息。
- 該語句不能引用隊列。
- 該語句不能包含不能更改且不能返回結(jié)果的條件語句(例如,WHERE 1 = 0)。
- 該語句不能指定READPAST鎖定提示。
- 該語句不能引用任何Service Broker QUEUE。
- 該語句不能引用同義詞。
- 該語句不能具有基于double / real數(shù)據(jù)類型的比較或表達式。
- 該語句不能使用TOP表達式。
在使用SqlDependency之前,首先需要啟用數(shù)據(jù)庫的服務器代理,默認情況下,SQL Server數(shù)據(jù)庫沒有啟用Service Broker。你可以使用SQL語句啟用Service Broker。
ALTER DATABASE DATABASE_NAME SET ENABLE_BROKER
下面是使用SqlDependency的簡單示例:
static string connectionString = @"your connect string"; static void Main(string[] args) { SqlDependency.Start(connectionString); getDataWithSqlDependency(); Console.WriteLine("Waiting for data changes"); Console.WriteLine("Press enter to quit"); Console.ReadLine(); SqlDependency.Stop(connectionString); } static DataTable getDataWithSqlDependency() { using (var connection = new SqlConnection(connectionString)) using (var cmd = new SqlCommand("SELECT productname FROM dbo.product;", connection)) { var dt = new DataTable(); var dependency = new SqlDependency(cmd); dependency.OnChange += new OnChangeEventHandler(onDependencyChange); connection.Open(); dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection)); return dt; } } static void onDependencyChange(object sender,SqlNotificationEventArgs e) { Console.WriteLine($"OnChange Event fired. SqlNotificationEventArgs: Info={e.Info}, Source={e.Source}, Type={e.Type}."); if ((e.Info != SqlNotificationInfo.Invalid) && (e.Type != SqlNotificationType.Subscribe)) { var dt = getDataWithSqlDependency(); Console.WriteLine($"Data changed. {dt.Rows.Count} rows returned."); } else { Console.WriteLine("SqlDependency not restarted"); } Console.ReadLine(); }
參考資料:
https://stackoverflow.com/questions/7588572/what-are-the-limitations-of-sqldependency
https://www.c-sharpcorner.com/UploadFile/87b416/working-with-sql-notification/
C#使用SqlDependency實現(xiàn)數(shù)據(jù)緩存
1、SqlDependency是什么:
SqlDependency對象表示應用程序和 SQL Server 實例間的查詢通知依賴關(guān)系。應用程序可以創(chuàng)建一個SqlDependency對象并進行注冊以通過OnChangeEventHandler事件處理程序接收通知。
它提供了這樣一種能力:當被監(jiān)測的數(shù)據(jù)庫中的數(shù)據(jù)發(fā)生變化時,SqlDependency會自動觸發(fā)OnChange事件來通知應用程序,從而達到讓系統(tǒng)自動更新數(shù)據(jù)(或緩存)的目的。
應用:數(shù)據(jù)實時性較高的場景、新聞、監(jiān)控數(shù)據(jù)等。
可以結(jié)合SignalR來實現(xiàn)web的實時數(shù)據(jù)更新。
2、使用方法:
1)sql server設(shè)置:ALTER DATABASE <DatabaseName> SET ENABLE_BROKER;語句讓相應的數(shù)據(jù)庫啟用監(jiān)聽服務,以便支持SqlDependency特性。
2)代碼:控制臺項目,web項目推薦把start放在Application_start方法中。
3)注意:查詢語句中不能使用*,表名要加[dbo].[xx]。sql語句要執(zhí)行。
conn =ConfigurationManager.ConnectionStrings["default"].ToString(); //Start和Stop方法 SqlDependency.Start(conn); Update(conn); private static void Update(string conn) { using ( SqlConnection connection = new SqlConnection(conn)) { //此處 要注意 不能使用* 表名要加[dbo] 否則會出現(xiàn)一直調(diào)用執(zhí)行 OnChange string sql = "select agent from [dbo].[info]"; using (SqlCommand command = new SqlCommand(sql, connection)) { connection.Open(); command.CommandType=CommandType.Text; dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); //必須要執(zhí)行一下command command.ExecuteNonQuery(); Console.WriteLine(dependency.HasChanges); } } } //update insert delete都會進入 private static void dependency_OnChange(object sender, SqlNotificationEventArgs e) { Console.WriteLine("onchange方法中:"+dependency.HasChanges); Console.WriteLine("數(shù)據(jù)庫數(shù)據(jù)發(fā)生變化"+DateTime.Now); //這里要再次調(diào)用 Update(conn); }
到此這篇關(guān)于C#_SqlDependency的使用的文章就介紹到這了,更多相關(guān)C# SqlDependency使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
json格式數(shù)據(jù)分析工具PageElement類分享(仿Session寫法)
json格式數(shù)據(jù)分析工具PageElement類分享,可像Session一樣自由獲取Json元素的Key與Value。并可方便與ADO進行交互2013-12-12