ExecuteNonQuery返回0?

时间:2018-12-16 01:52:59

标签: sql sql-server visual-studio-2017 sqlconnection

我有以下代码将哈希值和用户名与本地数据库( App_Users3

中的相应哈希值和用户名进行比较
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();                

var cmd = new SqlCommand(@"SELECT Username, Hash FROM App_Users3 WHERE Hash = @Hash AND Username = @Username");
cmd.Connection = con;

// savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("@Hash", SqlDbType.NVarChar, 50).Value = savedPasswordHash;
cmd.Parameters.Add("@Username", SqlDbType.NVarChar, 400).Value = AppUsername;

if (cmd.ExecuteNonQuery() > 0) 
{
    MessageBox.Show(" Query successful.. something matched..  ");
    // change page.. load a profile? 
}

它没有引发任何错误,但是我不明白为什么消息框没有显示。

1 个答案:

答案 0 :(得分:2)

ExecuteNonQuery 返回受修改数据语句(插入,更新,删除)影响的行。您应该对此类选择语句使用ExecuteScalar,例如返回用户的ID值。如果要返回多个值(多行或多列),则应使用ExecuteReader

这是修改您的代码以返回匹配用户的用户ID。

//-
    SqlConnection con = new SqlConnection();
    con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
    con.Open();                

    var cmd = new SqlCommand(@"SELECT UserId FROM App_Users3 WHERE Hash = @Hash AND Username = @Username");
    cmd.Connection = con;
    //savedPasswordHash = cmd.ExecuteScalar() as string;
    cmd.Parameters.Add("@Hash", SqlDbType.NVarChar, 50).Value= savedPasswordHash;
    cmd.Parameters.Add("@Username", SqlDbType.NVarChar, 400).Value = AppUsername;


    if (cmd.ExecuteScalar() != null) {
        MessageBox.Show(" Query successful..something matched..  ");
        //change page.. load a profile? 
    }
}