SqlStatement with' Where'不要排(行存在!)

时间:2015-08-04 09:14:49

标签: sql

我有这段代码但是当我调试时我无法进入dr.Read()

MembershipUser User = new MembershipUser();

SqlConnection conn = 
    new SqlConnection(ConfigurationManager
                          .ConnectionStrings["MVCForumContext"]
                          .ConnectionString);
conn.Open();

using (var GetName = new SqlCommand(
    "SELECT * FROM MembershipUser WHERE UserName = @UserName", conn
)){
    GetName.Parameters.AddWithValue("@UserName", Name);

    using (SqlDataReader dr = GetName.ExecuteReader())
    {
        if (dr.Read())
        {
            User.Id = dr.GetGuid(dr.GetOrdinal("Id"));
        }
    }
}
conn.Close();

我知道行存在,但它似乎没有用,有什么可以帮助?

1 个答案:

答案 0 :(得分:1)

另一种选择(不良做法 - 允许SQL注入攻击)允许您测试:尝试更改此行:

using (var GetName = new SqlCommand("SELECT * FROM MembershipUser WHERE UserName ='" + Name + "'", conn))

并删除:

GetName.Parameters.AddWithValue("@UserName", Name);

或者只需将参数@UserName更改为UserName

GetName.Parameters.AddWithValue("UserName", Name);