使用c#如何接收select语句的值(SQL)

时间:2013-10-07 10:25:49

标签: c# sql visual-studio-2010 sql-server-2008 c#-4.0

我想将select语句的结果值检索到字符串变量中。实际上我做了成功的登录编码,但之后我想根据他们的角色重定向页面从检索到数据库,如果是ADMIN,那么它进入ADMIN HOME PAGE,如果这是USER,那么它进入USER HOME PAGE。在我的代码下面,检查我错在哪里。

protected void btn_lpc_Login_Click(object sender, EventArgs e)
{
        string strCon = ConfigurationManager.ConnectionStrings["sessionname"].ConnectionString;
        string strSelect = "SELECT COUNT(*) FROM LOGIN_DETAILS WHERE EMAIL_ID=@EMAIL_ID AND PASSWORD =@PASSWORD";

    SqlConnection con = new SqlConnection(strCon);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = strSelect;

    SqlParameter username = new SqlParameter("@EMAIL_ID", SqlDbType.NVarChar, 36);
    username.Value = tbx_lpc_username.Text.Trim().ToString();
    cmd.Parameters.Add(username);

    SqlParameter password = new SqlParameter("@PASSWORD", SqlDbType.NVarChar, 50);
    password.Value = tbx_lpc_password.Text.Trim().ToString();
    cmd.Parameters.Add(password);

    con.Open();
    int result = (Int32)cmd.ExecuteScalar();

在这里我怀疑的话:

    if (result >= 1)
    {
        string strSelect2 = "SELECT ROLEID FROM LOGIN_DETAILS WHERE EMAIL_ID=@EMAIL_ID";

        if (srole == "USER")
        {
            Session.Add("usnm", tbx_lpc_username.Text);
            Response.Redirect("~/ADMIN_PAGES/LPC_ADM_HomePage.aspx");
        }
        else if (srole == "ADMIN")
        {
            Session.Add("usnm", tbx_lpc_username.Text);
            Response.Redirect("~/ADMIN_PAGES/LPC_ADM_SettingsPage.aspx");
        }
    }
    else
    {
        ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
    }
   }

1 个答案:

答案 0 :(得分:0)

    string strSelect2 = "SELECT ROLEID FROM LOGIN_DETAILS WHERE EMAIL_ID=@EMAIL_ID";
    cmd.CommandText = strSelect2;
    username = new SqlParameter("@EMAIL_ID", SqlDbType.NVarChar, 36);
    username.Value = tbx_lpc_username.Text.Trim().ToString();
    cmd.Parameters.Add(username);


    int roleId = (Int32)cmd.ExecuteScalar();

    if (roleId == 2) //USER
        {
            Session.Add("usnm", tbx_lpc_username.Text);
            Response.Redirect("~/ADMIN_PAGES/LPC_ADM_HomePage.aspx");
        }
        else if (roleId == 1) // ADMIN
        {
            Session.Add("usnm", tbx_lpc_username.Text);
            Response.Redirect("~/ADMIN_PAGES/LPC_ADM_SettingsPage.aspx");
        }