SqlDependency 初次

更新后的代码,始终读取最后更新的数据

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private SqlConnection sqlcon = new SqlConnection("Data Source=192.168.1.102;user id=sa;password=sa;Initial Catalog=JG;Pooling=False;");
private SqlCommand sqlcom = new SqlCommand();
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
SqlDependency.Start(sqlcon.ConnectionString);
}

private void Form1_Load(object sender, EventArgs e)
{
sqlcon.Open();
sqlcom.Connection = sqlcon;
update();
}
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event (for example, invalidate this cache entry).
update();
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
SqlDependency.Stop(sqlcon.ConnectionString);
}
private void update()
{

SqlCommand command1 = new SqlCommand("SELECT ID FROM dbo.gz", sqlcon);
SqlCommand command2 = new SqlCommand("SELECT ID FROM dbo.xm", sqlcon);
SqlDependency dependency = new SqlDependency();
dependency.AddCommandDependency(command1);
dependency.AddCommandDependency(command2);
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
//根新界面,这里始终读取表最后更新的数据
sqlcom.Parameters.Clear();
sqlcom.CommandText = "SELECT 工资 from gz where ID=17";
object j = sqlcom.ExecuteScalar();
label2.Text = j.ToString();
for (int i = 0; i < 9999; i++) { label1.Text = i.ToString(); }
//
}

private void button1_Click(object sender, EventArgs e)
{
sqlcom.CommandText = "select * from xm";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(sqlcom);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}



  在多次通知的情况下即数据库改变多次的情况,则只执行一次

  for (int i = 0; i < 9999; i++) { label1.Text = i.ToString(); }

  OnDependencyChange不能访问UI线程,所以在窗体构造函数中使用

 Control.CheckForIllegalCrossThreadCalls = false;

  SqlDependency不影响其他数据库操作,界面更新会阻塞OnDependencyChange

 private void button1_Click(object sender, EventArgs e)
        {
            sqlcom.CommandText = "select * from xm";
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sqlcom);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
        }

  

转载于:https://www.cnblogs.com/ninnd/p/3357673.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值