[英]How to get other column value if login successfull in c#
我有一个名为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;
}
ExecuteScalar()
函数仅返回top record value of the first column
的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.
}
}
}
如果UserID
和Role
在Users表中,则可以使用下面的代码。 它具有防止使用参数进行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;
}
使用查询
SqlDataReaer reader= Select *from Users where password="yourPassword"
然后您可以得到任何您想要的东西,即reader["userName"]
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.