读取整个数据库以检查值

时间:2013-11-16 06:56:57

标签: c# asp.net

我想检查整个数据库表,看看内容是否等于我的值。如果等于我的值,它将显示<div>标记。现在我成功地展示了<div>标签。但它只是从数据库读取一个值,这是数据库的第一个元素 在我读完第一个元素后,该函数停止搜索下一行。我想知道我该如何解决这个问题?据我所知,我可以将搜索内容存储到数据表中,然后逐个检索,但我不知道如何启动它。
这是我的代码。任何帮助将不胜感激。

public void showNotification()
{
    String MSGnotificationStatus = "";
    String PostNotificationStatus = "";
    try
    {
        MySqlConnection connStr = new MySqlConnection();
        connStr.ConnectionString = "Server = localhost; Database = healthlivin; Uid = root; Pwd = khei92;";
        String searchMesgNotification = "SELECT s.isRead FROM msgsession s, person m, contactfriend c WHERE m.PersonID = @pID AND m.PersonID = c.PersonID AND c.friendID = s.friendID";
        MySqlCommand cmdSearch = new MySqlCommand(searchMesgNotification, connStr);
        connStr.Open();
        cmdSearch.Parameters.AddWithValue("@pID", (String)Session["memberID"]);

        MySqlDataReader dtrRead = cmdSearch.ExecuteReader();

        if (dtrRead.Read())
        {
            MSGnotificationStatus = (String)dtrRead["isRead"];
        }

        dtrRead.Close();
        connStr.Close();

        String searchPostNotification = "SELECT p.isRead FROM post p, thread t, person m WHERE m.PersonID = @pID2 AND m.PersonID = t.PersonID AND t.threadID = p.threadID";
        MySqlCommand cmdSearch2 = new MySqlCommand(searchPostNotification, connStr);
        connStr.Open();
        cmdSearch2.Parameters.AddWithValue("@pID2", (String)Session["memberID"]);

        MySqlDataReader dtrRead2 = cmdSearch.ExecuteReader();
        if (dtrRead2.Read())
        {
            PostNotificationStatus = (String)dtrRead2["isRead"];
        }

        dtrRead2.Close();
        connStr.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

    /*After retrieve the value from the database do comparison to decide whether 
    to show the notification dialogue box*/
    if (MSGnotificationStatus.Equals("No") || PostNotificationStatus.Equals("No"))
    {
        notification.Visible = true;
        lblNPost.Text = "New Post @ Message!";
    }
    else
    {
        notification.Visible = false;
    }
}

1 个答案:

答案 0 :(得分:3)

使用SQL查找是否有任何通知,而不是阅读所有帖子。您的SQL将成为:

SELECT COUNT(p.isRead) as TotalUnreadPosts 
FROM post p, thread t, person m 
WHERE m.PersonID = @pID2 AND m.PersonID = t.PersonID 
AND t.threadID = p.threadID AND p.isRead = 'No'

然后,要使用TotalUnreadPosts

int totalUnreadPosts = cmdSearch.ExecuteScalar() as int;

现在您已经有了未读帖子的总数,您可以切换通知的显示:

if(totalUnreadPosts > 0) 
{
    notification.Visible = true;
}