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
  • 763
  • 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
  • 208,592
  • 21
  • 221
  • 278
  • 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
  • I suppose that I have misunderstood your code then. (about hashing) By the way, if you have the time and the answer helped you I think you could read [How does accepting an answer work](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Steve Nov 12 '15 at 21:01