[英]SqlDependency issues, Visual C++ .Net 3.5, SQL Server 2008
我在将SqlDependency服务与Windows Forms App集成时遇到一些问题,我希望有人可以帮助新手。 我只是想以此开头,我知道我的数据库连接字符串和查询语句是正确的。 此外,我知道在数据库上启用了服务代理。 发行:
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事件。 我假设自己正在做一些古怪的事情,但是我没有足够的洞察力来解决。 谢谢。
经过无休止的研究之后,我遇到的问题根源于表的设计而不是代码的设计。 以下是我为解决该问题而更改的三件事:
该语句不能引用大型对象类型:text,ntext和image。
我使用“ ntext”作为其中一列的数据类型。
该语句不能使用星号( *)或table_name。* 语法指定列。
最初,我使用通配符从表中选择数据。
SELECT语句中的投影列必须明确声明,并且表名必须由两部分组成。
我在SELECT语句中没有使用两部分的表名,即“ Table_name”而不是“ dbo.Table_name”。
这是一个很难固定的问题,我希望这可以帮助其他遇到类似问题的人。 我在对问题的初始描述中打错了口号,因为我的查询虽然完全合法,但对SqlNotifications无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.