检查ASP.NET C#中的MS Access数据库是否返回任何行

时间:2017-04-26 10:32:02

标签: c# asp.net ms-access

我有这段代码:

cmd.Parameters.AddWithValue("@userName", txtLoginUserName.Text.Trim());
cmd.Parameters.AddWithValue("@password", txtLoginPassword.Text.Trim());

string sqllogin = "SELECT [username],[password] FROM users WHERE ([username] = @userName AND [password] = @password) ";

try
{
    con.Open();
    cmd.CommandText = sqllogin;
    int store = cmd.ExecuteNonQuery();

    con.Close();
    Label4.Text = store.ToString();
}
catch (Exception ex)
{
    con.Close();
}

每当执行时,它会在0中打印出label4。这是检查返回行数的正确方法吗?

2 个答案:

答案 0 :(得分:2)

cmd.Parameters.AddWithValue("@userName", txtLoginUserName.Text.Trim());
cmd.Parameters.AddWithValue("@password", txtLoginPassword.Text.Trim());

string sqllogin = "SELECT count(*) FROM users WHERE ([username] = @userName AND [password] = @password) ";

try
{
    con.Open();
    cmd.CommandText = sqllogin;
    var store = cmd.ExecuteScalar();

    con.Close();
    Label4.Text = store.ToString();
}
catch (Exception ex)
{
    con.Close();
}

答案 1 :(得分:1)

要回答您的具体问题,ExecuteNonQuery()应返回受影响的行数。但是那个查询对你来说并没有太大的帮助。

如果你只想知道有多少数据行与un / pwd组合相匹配,那么我会将其更改为

"SELECT COUNT([username]) FROM users WHERE ([username] = @userName AND [password] = @password) ";

我仍然没有看到对你有多大用处,但你知道你想要做什么:-)