1

i'm develpoing a login server and i've come to this problem: I'm using this SQL function to get password where username matches:

SELECT password FROM users WHERE username='someusername';

On c# i'm using this code:

string cmdString = ("SELECT password FROM users WHERE username='@username'");
        using (var con = new MySqlConnection(CNN_STRING))
        {
            con.Open();
            var cmd = new MySqlCommand(cmdString, con);
            cmd.Parameters.AddWithValue("@username", user);
            return cmd.ExecuteScalar().ToString();                
       }

On MySQL workbench it works normally but on c# i always get a null value, and if i try to use cmd.ExecuteReader and Reader.Read() instead of cmd.ExecuteScalar() i get a exception saying that i haven't run Reader.Read() though i did.

Pau C
  • 773
  • 4
  • 20
  • 1
    You shouldn't need to enclose @username in single-quotes; the parameterization should take care of that automatically. – Uueerdo Nov 12 '15 at 18:51

1 Answers1

0

Do not put the parameter placeholder between single quotes. In this way your parameter placeholder becomes a literal string and thus there is no username named '@username'

string cmdString = ("SELECT password FROM users WHERE username=@username");

Said that, please be aware that storing passwords in plain text inside your database is a big security risk. You should store just the hash of the password

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • That was it, for some reason at the begining it wasn't working without quotes, now it does. And i am using password hashes. – Pau C Nov 12 '15 at 20:43