0

我有一个用于访客登录的信息亭,当他们登录时,它会将数据发送到 SQL 数据库。然后,我将这些数据拉入数据集,然后拉入监控应用程序上的 datagridview。该数据每 15 秒刷新一次。

如何在不每次都获取所有数据的情况下更新此数据集/datagridview?最初的拉动大约是 500 行,我不想每次都拉动所有相同的 500 行。我想检查是否有任何新记录并将它们添加到数据集中。

这是我获取数据的代码

private void UpdateUsers()
    {
        SqlConnection conn = ConnectSQL("10.100.25.250", "bhi_kiosk");
        var query = new SqlCommand("SELECT * FROM Users WHERE uStatus=1", conn);
        SqlDataReader read = null;
        listView1.Items.Clear();

        conn.Open();
        read = query.ExecuteReader();
        var dt = new DataTable();
        dt.Load(read);
        query.Connection.Close();
        dataGridView1.DataSource = dt;
}
4

1 回答 1

2

如果您在开始时加载数据:

DataTable dt = new DataTable();
DateTime lastChange = new DateTime(1753, 1, 1);
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    dataGridView1.DataSource = dt;
    UpdateUsers();
}

然后新数据表合并到旧数据表中:

private void UpdateUsers()
{
    SqlConnection conn = ConnectSQL("10.100.25.250", "bhi_kiosk");
    var query = new SqlCommand("SELECT * FROM Users WHERE uStatus=1 AND LastChange > @LastChange ORDER BY LastChange", conn);
    var lastChangeparameter = query.Parameters.Add("@LastChange", SqlDbType.DateTime);
    lastChangeparameter.Value = lastChange;
    //listView1.Items.Clear();
    conn.Open();
    using (SqlDataReader read = query.ExecuteReader())
    {
        using (var dt_merge = new DataTable())
        {
            dt_merge.Load(read);
            dt.Merge(dt_merge);
            if (dt.Rows.Count > 0)
            {
                lastChange = (DateTime)dt.Rows[dt.Rows.Count - 1]["LastChange"];
            }
        }
    }
    conn.Close();
}

You will get what you want. Couple of pointers: there really should be a try ... catch block to ensure conn is disposed in case of error. Query depends on order by LastChange because next reading time is taken from maximum (LastChange). You use datetime from server to avoid possibility of loosing a record if client time is not perfectly aligned with server time.

于 2012-05-21T14:39:30.977 回答