日期:2014-05-20 浏览次数:20975 次
use master go create database dbTest go use dbTest go create table test(id int identity(1,1),name varchar(10)) insert into test(name)select 'aa' insert into test(name)select 'bb' insert into test(name)select 'cc' insert into test(name)select 'dd' insert into test(name)select 'ee' go alter database dbTest set enable_broker
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication10
{
public partial class Form1 : Form
{
//拖一个DataGridView到Form中
public Form1()
{
InitializeComponent();
}
//变量
string connString = "server=localhost;uid=sa;pwd=sqlgis;database=dbTest";
System.Data.SqlClient.SqlConnection conn = null;
System.Data.SqlClient.SqlCommand command = null;
//出示化
private void Form1_Load(object sender, EventArgs e)
{
conn = new System.Data.SqlClient.SqlConnection(connString);
command = conn.CreateCommand();
command.CommandText = "select id,name from dbo.test where id <>4 order by id desc ";
SqlDependency.Start(connString);//启动
GetData();//获取数据
}
private void GetData()
{
command.Notification = null;//清除
SqlDependency dependency = new SqlDependency(command);//设置通知
dependency.OnChange += new OnChangeEventHandler(sqlDependency_OnChange);//通知事件
using (SqlDataAdapter adapter =new SqlDataAdapter(command)) //查询数据
{
System.Data.DataSet ds = new DataSet();
adapter.Fill(ds,0,3, "test");
dataGridView1.DataSource = ds.Tables["test"];
}
}
void sqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
//因为是子线程,需要用invoke方法更新ui
if (this.InvokeRequired)
{
this.Invoke(new OnChangeEventHandler(sqlDependency_OnChange), new object[] { sender, e });
}