我想将用户名和密码带到数据库,并根据插入的用户名和密码获取用户角色,但此代码不起作用
-mtune=x
以及应该将角色检入数据库的c#代码,如果没有管理员和客户端页面,则将我重定向到服务器页面: -
public bool Login(out string Msg)
{
bool b = true;
Msg = "";
SqlConnection con = new SqlConnection(connection.connectstr);
try
{
con.Open();
SqlCommand com = new SqlCommand("user_proc", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@u_name", SqlDbType.NVarChar).Value = this.u_name;
com.Parameters.Add("@u_password", SqlDbType.NVarChar).Value = this.u_password;
com.ExecuteNonQuery();
con.Close();
b = true;
}
catch (Exception ex)
{
con.Close();
Msg = ex.Message;
b = false;
}
return b;
}
,执行该任务的数据库过程是:
protected void btn_login_Click(object sender, EventArgs e)
{
my_user u = new my_user();
u.u_name = TextBox1.Text;
u.u_password = TextBox2.Text;
string m="";
if (!u.Login(out m))
{
lbl_role.Text = "error";
}
else
{
if (u.u_role == "admin")
{
Response.Redirect("testclient.aspx");
}
else Response.Redirect("testserver.aspx");
}
}
答案 0 :(得分:0)
在DB中,您有一个名称,传递和角色的用户表
所以,角色是否为管理员
然后,我建议 在您的应用中使用SqlExecuteScalar
进行检查public bool IsAdmin(string u_name, string u_password)
{
string role="";
string sql = "select u_role from user_sys
where u_name=@u_name and u_password= @u_password";
using (SqlConnection conn = new SqlConnection(connection.connectstr))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add(new SqlParameter("@u_name", u_name));
cmd.Parameters.Add(new SqlParameter("@u_password", u_password));
try
{
conn.Open();
role = cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
//handle error
}
}
return role == "admin";
}
最后称之为
string u_name = TextBox1.Text;
string u_password = TextBox2.Text;
if (IsAdmin(u_username,u_password))
//it is admin
else
//it is not admin
再见,玩得开心!