考虑这个例子:检测SQL数据库改变
INSERT INTO [Table] (column1)
SELECT value1
如果我执行在SSMS此命令,在关于一个C#窗体应用程序,你会我需要为了认识这个事件呢?事件发生时,应用程序显示一个MessageBox
。我似乎无法解决这个问题或找到有用的数据。我试图使用SqlDependency
但我没有任何运气。如果那是我需要走下去的道路,任何人都可以帮助我理解这个概念,让它更好一点?
考虑这个例子:检测SQL数据库改变
INSERT INTO [Table] (column1)
SELECT value1
如果我执行在SSMS此命令,在关于一个C#窗体应用程序,你会我需要为了认识这个事件呢?事件发生时,应用程序显示一个MessageBox
。我似乎无法解决这个问题或找到有用的数据。我试图使用SqlDependency
但我没有任何运气。如果那是我需要走下去的道路,任何人都可以帮助我理解这个概念,让它更好一点?
如果你想检测变化,而不是只是插入,你可以使用SQL Dependency来实现这一点。你有没有阅读并尝试链接中的例子?
Heres a nice 'tutorial/example' that works and runs you through the basics。
Heres a nice overview of Query Notifications.
低级实现是由暴露服务器侧功能,使你的通知请求执行命令的SqlNotificationRequest类提供。
高级实现由SqlDependency类提供,该类提供了源应用程序和SQL Server之间的通知功能的高级抽象,使您可以使用依赖关系来检测服务器。在大多数情况下,这是通过使用SQL Server的.NET Framework数据提供程序的托管客户端应用程序来利用SQL Server通知功能的最简单和最有效的方法。
此外,使用ASP.NET 2.0或更高版本构建的Web应用程序可以使用SqlCacheDependency辅助类。
这是因为基本为“A的SqlDependency对象可以用,以便在查询结果从那些最初检索不同,以检测一个SqlCommand相关联。”
必须首先Enable Query Notifications,并按照Creating a Query for Notification
void Initialization()
{
// Create a dependency connection.
SqlDependency.Start(connectionString, queueName);
}
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object which directly references (no synonyms) the data you want to check for changes.
using (SqlCommand command=new SqlCommand("SELECT value1 FROM [Table]", connection))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency=new SqlDependency(command);
// Maintain the refence in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange+=new OnChangeEventHandler(OnDependencyChange);
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
// Handler method
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event (for example, invalidate this cache entry).
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(connectionString, queueName);
}
这不会给我插入的行 – 2018-03-02 11:32:09
如果我理解你,你要当你的SQL Server运行的刀片选择在您的C#应用程序触发一个事件? – paqogomez 2014-09-04 16:12:46
@paqogomez正确!有点像ssms中的触发器,我想在C#中触发一个# – Volearix 2014-09-04 16:14:56
你想检测什么时候从C#应用程序中的数据库中发生变化? SQL Server不会推送通知,所以你将不得不轮询一些东西。你可以做的一件事就是在需要的地方添加一个'INSERT TRIGGER',它从日志记录到审计表和'SELECT'。 – Zer0 2014-09-04 16:15:10