class Program
{
static string connectionStr = "Data Source=.;Initial Catalog=Test;Integrated Security=True";
static void Main(string[] args)
{
SqlDependency.Start(connectionStr);//传入连接字符串,启动基于数据库的监听
UpdateGrid();
Console.Read();
SqlDependency.Stop(connectionStr);
}
private static void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(connectionStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT id,name FROM [dbo].[User]", connection))
{
command.CommandType = CommandType.Text;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (SqlDataReader sdr = command.ExecuteReader())
{
Console.WriteLine();
while (sdr.Read())
{
Console.WriteLine("ID:{0}\t数据:{1}\t", sdr["id"].ToString(), sdr["name"].ToString());
}
sdr.Close();
}
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
{
UpdateGrid();
}
}
}