首先 开启数据库Service Broker (使用master权限)
ALTER DATABASE DBName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE DBName SET ENABLE_BROKER;
具体查询方式:
class Program
{
static string connectionString = "Server=.;Database=testDemo;User Id=sa;Password=123456;MultipleActiveResultSets=true";
static void Main(string[] args)
{
SqlDependency.Start(connectionString);//传入连接字符串,启动基于数据库的监听
UpdateGrid();
Console.Read();
SqlDependency.Stop(connectionString);//传入连接字符串,关闭基于数据库的监听(一旦关闭,则只会识别一次,然后就自定关闭了)
}
private static void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(ConectionStr))
{
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
using (SqlCommand command = new SqlCommand("SELECT ZhifuSingle,DibangNo,JinE,ZhifuOrder FROM dbo.ZhifuInfos", connection))
{
command.CommandType = CommandType.Text;
//OPCommon.LogWrite.WriteLog(ConectionStr);
connection.Open();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
//Console.WriteLine();
DataTable DT = new DataTable();
DT.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
ZhifuInfos ZhifuResult = new ZhifuInfos();
if (DT != null && DT.Rows.Count > 0)
{
DataRow DR = DT.Rows[0];
ZhifuResult.ZhifuSingle = DR["ZhifuSingle"].ToString();//支付标记
ZhifuResult.DibangNo = DR["DibangNo"].ToString();//地磅编号;
ZhifuResult.JinE = ConvertType.GetDecimal(DR["JinE"]);//金额;
ZhifuResult.ZhifuOrder = DR["ZhifuOrder"].ToString();//支付订单号;
}
if (!string.IsNullOrWhiteSpace(ZhifuResult.ZhifuSingle) && ZhifuResult.ZhifuSingle == ZhifuSingle)//支付完成
{
ShowThrendEndzhifu();//支付完成显示称重数据
}
ZhifuSingle = string.Empty;
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= dependency_OnChange;
if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
{
UpdateGrid();
}
}
}
使用请注意:SqlNotificationType.Change 内包含数据所有操作数据包含 delete 删除,update 修改 insert插入都会触发此事件。