0

Basically what I'm trying to achieve is the following:-

I have a text box field with a value, I want to check this value against the value in the SQL Server database if there's a match then do a particular task.

This is what I have so far:

SELECT        userID, username , password
FROM           Users
WHERE        (username = textboxUsername.text) AND (password = textboxPassword.text

But it doesnt seem to work for me, I think I'm almost doing it correctly?

Also would I be better off using a data set or just a bog stand sql command as there will be other queries to be carried out?

Many thanks

mjsey
  • 1,938
  • 5
  • 18
  • 28

2 Answers2

1

You need to create the query using the values from the textboxes.

You can do this with named parameters for example to ensure values are escaped properly:

SqlCommand cmd = new SqlCommand();
cmd.CommandText = @"SELECT        userID, username , password
FROM           Users
WHERE        (username = @username) AND (password = @password)";

cmd.Parameters.AddWithValue("@username", textboxUsername.Text);
cmd.Parameters.AddWithValue("@password", textboxPassword.Text);
...
Stelian Matei
  • 11,553
  • 2
  • 25
  • 29
  • I'm trying to do this using the SQLCommand Control from the tool box but still having problems – mjsey Feb 16 '12 at 23:00
1

Expanding a little on mazzucci's answer:

using (var con = new SqlConnection("connection string"))
{
    con.Open();
    var cmd = new SqlCommand(@"SELECT userID, username, password FROM Users WHERE (username = @username) AND (password = @password)");
    cmd.Parameters.AddWithValue("@username", textboxUsername.Text);
    cmd.Parameters.AddWithValue("@password", textboxPassword.Text);

    if (cmd.ExecuteNonQuery() > 0)
    {
        //They were the same
    }
}

However, consider that whatever you're doing looks fairly dangerous. I think Eric Lippert has made more than a few posts on SO about the dangers of passwords and authentication stuff in general.

Such as this one: Does salt need to be random to secure a password hash?

Community
  • 1
  • 1
Jesse
  • 307
  • 1
  • 5
  • I also seem to get a return value of -1 regardless of a match or not? Should I not be using the .ExecuteScalar() method? – mjsey Feb 16 '12 at 23:46