我有一些問題整合SqlDependency服務與我的Windows窗體應用程序,我希望有人可以幫助一個菜鳥。我只是想以此爲序,我知道我的數據庫連接字符串和我的查詢語句是正確的。此外,我知道服務代理已在我的數據庫上啓用。發行:SqlDependency問題,Visual C++ .Net 3.5,SQL Server 2008
SELECT is_broker_enabled FROM sys.databases WHERE name = 'Database'
從查詢返回1。
我開始依賴我的主要形式加載事件,像這樣:
SqlDependency::Stop(Get_DB_String());
SqlDependency::Start(Get_DB_String());
然後我從數據庫中提取如下:
bindingSource->DataSource = GetData("Select * From Table",
Get_DB_String(),
dataAdapter);
dataGridView->DataSource = bindingSource;
哪裏的GetData被定義爲:
DataTable^ GetData(String^ sqlCommand, String^ connectionString, SqlDataAdapter^ adapter)
{
SqlConnection^ Connection = gcnew SqlConnection(connectionString);
SqlCommand^ command = gcnew SqlCommand(sqlCommand,Connection);
command->Notification = nullptr;
SqlDependency^ dependency = gcnew SqlDependency(command);
dependency->OnChange += gcnew OnChangeEventHandler(this, &LabSchedule::Form1::OnChange);
adapter->SelectCommand = command;
DataTable^ table = gcnew DataTable;
adapter->Fill(table);
return table;
}
而我的更改處理程序定義如下:
System::Void OnChange(System::Object^ sender, SqlNotificationEventArgs^ e)
{
ISynchronizeInvoke^ i = (ISynchronizeInvoke^)this;
if (i->InvokeRequired)
{
OnChangeEventHandler^ tempDelegate =
gcnew OnChangeEventHandler(this, &LabSchedule::Form1::OnChange);
array<System::Object^>^ args = { sender, e };
i->BeginInvoke(tempDelegate, args);
return;
}
SqlDependency^ dependency = (SqlDependency^)sender;
dependency->OnChange -= gcnew OnChangeEventHandler(this, &LabSchedule::Form1::OnChange);
if(dependency->HasChanges)
{
// This is where I check the properties of the notification
MessageBox::Show(e->Info.ToString() + "\n" + e->Source.ToString() + "\n" + e->Type.ToString());
}
}
當我從我的本地客戶端更改數據庫中的某些內容時,它會觸發更改事件,並且看起來一切正常。但是,當我從另一臺機器上的客戶端啓動更改時,OnChange事件永遠不會被觸發。我假設我做的事很古怪,但我沒有洞察力。謝謝。
作爲更新,當事件在本地觸發時,我檢查了SqlNotificationEventArgs參數的「Type」屬性,它將返回「Subscription」指示訂閱失敗。 「Info」屬性爲「無效」。 MSDN說:「提交的命令包含一個不支持通知的語句(例如,INSERT或UPDATE)。」我無法想象一個SELECT語句是無效的;是不是你如何看待數據庫開始? – 2012-02-09 20:39:01
此外,我嘗試了在另一個線程上遇到的提示,以顯式聲明我想從我的表中檢索的字段,而不是使用通配符*方法。這看起來沒有什麼區別。 – 2012-02-13 13:29:14