0

我有一张名为 Users 的表,它有 4 列

  • 用户身份
  • 用户名
  • 密码
  • 角色

如果登录成功,我想知道 UserId 和 Role 值,

对于登录验证,我编写了以下函数,

 private bool ValidationFunction(string username, string pwd)
    {
        bool boolReturnValue = false;

        string s = "correct connection string";
        SqlConnection con = new SqlConnection(s);
        con.Open();
        string sqlUserName;
        sqlUserName = "SELECT UserName,Password FROM Users WHERE UserName ='" + username + "' AND Password ='" + pwd + "'";
        SqlCommand cmd = new SqlCommand(sqlUserName, con);

        string CurrentName;
        CurrentName = (string)cmd.ExecuteScalar();

        if (CurrentName != null)
        {
            boolReturnValue = true;
        }
        else
        {
            Session["UserName"] = "";
            boolReturnValue = false;
        }
        return boolReturnValue;
    }
4

3 回答 3

4

ExecuteScalar()函数只返回top record value of the first column. 所以你需要ExecuteReader()改用。

其他重要的事情是您最好使用参数化查询将这些用户键入的值传递到数据库中。您可以通过这种方式进行 sql 注入攻击。

尝试这个:

using (SqlConnection cnn = new SqlConnection("yourConnectionString"))
{
    string sql= "select userId,role from users " +
                "where username=@uName and password=@pWord";

    using (SqlCommand cmd = new SqlCommand(sql,cnn))
    {
         cmd.Parameters.AddWithValue("@uName", username);
         cmd.Parameters.AddWithValue("@pWord", pwd);

         cnn.Open();
         SqlDataReader reader = cmd.ExecuteReader();

         while (reader.Read())
         {
            //get the reader values here.
         }
    }
}
于 2013-09-09T17:09:30.297 回答
1

如果UserID并且Role在用户表中,您可以使用下面的代码。它具有使用参数防止 SQL 注入攻击的额外好处。

private class User
{
    public int UserID {get;set;}
    public string Role {get;set;}
    public string UserName {get;set;}

}
private bool ValidationFunction(string username, string pwd, out User)
    {
        bool boolReturnValue = false;

        string s = "correct connection string";
        SqlConnection con = new SqlConnection(s);
        con.Open();
        string sqlUserName;
        sqlUserName = "SELECT UserName,Password,UserID,Role FROM Users WHERE UserName =@usr AND Password=@pwd";
        SqlCommand cmd = new SqlCommand(sqlUserName, con);
        cmd.Parameters.Add(new SqlParameter("usr", username));
        cmd.Parameters.Add(new SqlParameter("pwd", pwd));

        SqlDataReader reader = command.ExecuteReader();

        if (reader.Read())
        {
            boolReturnValue = true;
            User = new User(){UserName = username, UserID=reader.GetInt32(2), Role=reader.GetString(3)};
        }
        else
        {
            Session["UserName"] = "";
            boolReturnValue = false;
        }
        return boolReturnValue;
    }
于 2013-09-09T17:17:22.153 回答
-1

使用查询

SqlDataReaer reader= Select *from Users where password="yourPassword"

然后你可以得到你想要的任何东西,比如reader["userName"]等等

于 2013-09-09T17:21:15.750 回答