c# - Must declare the scalar variable "@UserName" -


i have make simple login not crash when insert browser (") needed parameterize query string reason im gettin error saying:

must declare scalar variable "@username"

here code

private void dosqlquery()  {     try      {         sqlconnection conn = new sqlconnection(configurationmanager.connectionstrings["rolaconnectionstring"].connectionstring);         conn.open();         string checkuser = "select * userdata username = @username";         sqlcommand com = new sqlcommand(checkuser, conn);         com.parameters.addwithvalue("@username", txtusername.text.trim());          int temp = convert.toint32(com.executescalar().tostring());         conn.close();         if (temp == 1)         {             conn.open();             string checkpassword = "select password userdata username = @username";             sqlcommand passconn = new sqlcommand(checkpassword, conn);             com.parameters.addwithvalue("@username", txtusername.text.trim());             string password = passconn.executescalar().tostring();             conn.close();             if (password == txtpassword.text)             {                 session["new"] = txtusername.text;                 response.write("password correct");                 response.redirect("~/loggedin.aspx");             }             else             {                 response.write("password not correct");             }         }         else         {             response.write("username not correct");         }     }     catch(exception e)     {         response.write(e.tostring());     } } 

you referencing wrong command in inner if statement:

string checkpassword = "select password userdata username = @username"; sqlcommand passconn = new sqlcommand(checkpassword, conn); com.parameters.addwithvalue("@username", txtusername.text.trim()); ^^^--  should passconn  

as result, second command never gets parameter added error mention. case sensitivity may problem, depends on collation of database - sql server case-insensitive default.

some other suggestions not related problem:

  • wrap commands , connection in using statements
  • query username , password in 1 query (where username = @username , password = @password). hackers first search valid usernames, try hack password using dictionary attacks. trying find matching combination much harder.
  • do not store passwords in plain text - use salted hash
  • or use built-in security providers rather rolling own.

Comments

Popular posts from this blog

c# - SharpSsh Command Execution -

python - Specify path of savefig with pylab or matplotlib -

How to run C# code using mono without Xamarin in Android? -