Hi, I have a bit of code that checks a user's password after they try to login from a barebone login form. I've removed password encryption and try/catches to simplify the code. What I want to know: Can I do this faster/better/easier? public bool verifyUser(string username, string password) { //try //{ sqlConn = new SqlConnection(connectionString); sqlConn.Open(); SqlCommand selectCommand = sqlConn.CreateCommand(); selectCommand.Parameters.Add(new SqlParameter("@username", username)); selectCommand.CommandText = "SELECT password FROM usersTable WHERE username = @username"; SqlDataReader selectCommandReader = selectCommand.ExecuteReader(); selectCommandReader.Read(); if ((string)selectCommandReader["password"] == password) { return true; } else { return false; } //} Code (markup): I feel as if it could be more simple, but I'm not sure how.
I believe that you get an exception if the user does not exist and you run selectCommandReader.Read(); You can likely cut down on some overhead by adding if(selectCommandReader.Read()) { if ((string)selectCommandReader["password"] == password) { return true; } else { return false; } } else { return false; } Besides that, I don't see any steps you can cut out.
cool thanks for your reply question about what you wrote: if(selectCommandReader.Read()) { } Code (markup): So SelectCommandReader.Read() will be false if the query returns nothing? Previously I was contemplating checking for a null or something like that... at the moment the whole thing is in a try/catch, and in the catch I close the sqlConn and return false. I would much rather use your suggestion if does what I think it does.
Correct. .Read() will return a boolean false if there are no results found (and true if their is). This is also useful for going through multiple results using a while loop while(selectCommandReader.Read()) { } Will execute until it gets to the end of the result set.