简体   繁体   中英

How can I retrieve specific data from sql in c#?

I have a database with the following table:

用户表

I am trying to get the role of the current username so I can redirect that person to the right page. I tried it with the if clause (acc.u_role == 1), but it doesn't work unfortunately.

    public ActionResult Verify(User acc)
    {
        connectionString();
        con.Open();
        com.Connection = con;
        com.CommandText = "select * from Users where u_username = '"+acc.u_username+"' and u_password ='"+acc.u_password+"'";

        dr = com.ExecuteReader();
        if (dr.Read())
        {
            if (acc.u_role == 1) { 
                con.Close();
                return View("AdminHome");
            }
            else
            {
                con.Close();
                return View("UserHome");
            }
        }
        else
        {
            con.Close();
            return View("Error");
        }
    } 

Where are you setting acc.u_role?

It looks like you're reading the data and then not using it. dr[5] should contain the role from the database

        dr = com.ExecuteReader();
        if (dr.Read())
        { 

            if (dr[5] == 1) { 
                con.Close();
                return View("AdminHome");
            }

I already found a solution to my answer, here it is:

 if (dr.Read())
            {
                if (Convert.ToInt32(dr["u_role"]) == 1) {
                    con.Close();
                    return View("AdminHome");
                }
                else
                {
                    con.Close();
                    return View("UserHome");
                }
            }
            else
            {
                con.Close();
                return View("Error");
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM