[英]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.