使用C#监视SQL Server表的更改可以通过以下步骤实现:
下面是一个示例代码,演示如何使用C#监视SQL Server表更改:
using System;
using System.Data.SqlClient;
namespace TableChangeMonitoring
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Your SQL Server connection string";
string tableName = "Your table name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string createTriggerQuery = $"CREATE TRIGGER TableChangeTrigger ON {tableName} AFTER INSERT, UPDATE, DELETE AS BEGIN SELECT 1 END";
using (SqlCommand command = new SqlCommand(createTriggerQuery, connection))
{
command.ExecuteNonQuery();
}
using (SqlCommand command = new SqlCommand($"SELECT * FROM {tableName}", connection))
{
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += Dependency_OnChange;
using (SqlDataReader reader = command.ExecuteReader())
{
// Process initial data
while (reader.Read())
{
// Process each row
}
}
}
Console.WriteLine("Press any key to stop monitoring...");
Console.ReadKey();
string dropTriggerQuery = $"DROP TRIGGER TableChangeTrigger ON {tableName}";
using (SqlCommand command = new SqlCommand(dropTriggerQuery, connection))
{
command.ExecuteNonQuery();
}
connection.Close();
}
}
private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
// Handle table change notification
}
}
}
请注意,上述示例代码仅演示了如何使用C#监视SQL Server表的更改,并没有提及任何特定的腾讯云产品。根据你的具体需求,你可以选择适合的腾讯云产品来存储和处理SQL Server表的更改数据。
领取专属 10元无门槛券
手把手带您无忧上云