通过网上的资料找到了SqlDependency类的使用方法,但没实现成功。望指点迷津~
下面是主程序入口设置对SqlDependency的监听
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
string _connStr = "Data Source=LAPTOP-B1KP96US;Initial Catalog=User;Integrated Security=True";
SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
SqlDependency.Stop(_connStr);//传入连接字符串,启动基于数据库的监听
}
}
然后是应用程序处
private void UpdateGrid()
{
string _connStr = "Data Source=LAPTOP-B1KP96US;Initial Catalog=User;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(_connStr))
{
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
using (SqlCommand command = new SqlCommand("select Channel_ID, Channel_Name, Channel_User, Channel_Route, Channel_Date From[dbo].[Channel]", connection))
{
command.CommandType = CommandType.Text;
connection.Open();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
SqlDataReader sdr = command.ExecuteReader();
Console.WriteLine();
while (sdr.Read())
{
Console.WriteLine("Channel_ID:{0}\tChannel_Name:{1}\tChannel_User:{2}\tChannel_Route:{3}\tChannel_Date:{4}", sdr["Channel_ID"].ToString(), sdr["Channel_Name"].ToString(),sdr["Channel_User"].ToString(), sdr["Channel_Route"].ToString(), sdr["Channel_Date"].ToString());
}
sdr.Close();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
{
UpdateGrid();
this.channelTableAdapter.Fill(this.userDataSet.Channel);
}
}
不知道哪里出错了,望指点~