简体   繁体   中英

Why is this SQL statement giving me an invalid column name error?

I'm trying to use an SQL select statement to read from a database to validate a login form. The problem I'm having is its telling me its an invalid column name.

SELECT * FROM users
WHERE [username] = @theusername  
AND [password] = @thepassword

where @theusername is a parameratized value of "Rymo_18", and the password is, for the sake of argument, "password".

The errors I get are:

Invalid column name 'Rymo_18'.

Invalid column name 'password'

Don't know why I'm getting those errors. I've tried swapping the values around the = sign, tried using values directly (username = "Rymo_18") and all other matters of fiddling to fix it, and I've had no luck. There are no other tables called 'user' within my Database.

EDIT: Here's the code as it appears in the C# I'm using:

string user = unametext.Text;
        string pword = pwordtext.Text;

        string connectionstring = WebConfigurationManager.ConnectionStrings["elmtreeconnect"].ConnectionString;

        SqlConnection myconnection = new SqlConnection(connectionstring);

        myconnection.Open();

        string query = "SELECT * FROM users WHERE (username= @theusername OR email = @theusername) AND password = @thepassword";

        SqlCommand attemptLogin = new SqlCommand(query, myconnection);

        attemptLogin.Parameters.AddWithValue("@theusername", user);
        attemptLogin.Parameters.AddWithValue("@thepassword", pword);

        SqlDataReader rdr = attemptLogin.ExecuteReader();

        if (rdr.HasRows)
        {
            Session["user"] = rdr["username"].ToString();
            Session["id"] = rdr["id"].ToString();
            Session["type"] = rdr["accountType"].ToString();

            Response.Redirect("loginsuccess.aspx");
        }
        else
        {
            unametext.Text = "";
            pwordtext.Text = "";

            statusLabel.Text = "Login failed. Please try again, or contact info@elmtree.co.uk for assistance";

        }

Thanks for the help!

string query = "select 1 from users where username=@theusername and password=@password";
...
if(rdr.Read()){
...
}

exists should be used in if exists(select...)

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