Gizzy
Gizzy

Reputation: 27

Selecting two columns for SqlCommand class

I would like to find out whether there is a way to select two columns in the same table for a single SqlCommand which would be afterwards used for comparison between data in the two columns and data in two textBoxes:

Below are two strings what I use at the moment for SqlCommand class and would like to put them together:

String str1 = String.Format("SELECT * FROM [employeeAccount] WHERE [User Name] LIKE '{0}'", txtUserName.Text);
String str2 = String.Format("SELECT * FROM [employeeAccount] WHERE [Password] LIKE '{0}'", txtPassword.Text);

Upvotes: 0

Views: 114

Answers (3)

Habib
Habib

Reputation: 223322

Few things to improve....

  1. Do not use string concatenation/formatting to form SQL queries, you are prone to SQL injection. Parametrize your queries. Use SqlParameter
  2. Important!. Do not use LIKE to compare against user name and password, you probably want exact match using =
  3. You need to combine two conditions using AND operator.

So your code should look like:

using(SqlConnection connection = new SqlConnection("yourConnectionString"))
using (
    SqlCommand command =
        new SqlCommand(
            "SELECT * FROM [employeeAccount] WHERE [UserName] = @userName AND [Password] = @password",
            connection))
{
    command.Parameters.AddWithValue("@username", txtUserName.Text);
    command.Parameters.AddWithValue("@password", txtPassword.Text);
    connection.Open();
    //,... execute command
}

One last thing to add, do not store password text in database, instead store their hashes, see: How to store passwords *correctly*?

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460238

Just use AND in your sql query and sql-parameters to prevent sql-injection:

string sql = @"SELECT * FROM [employeeAccount] 
               WHERE [User Name] = @UserName
                 AND [Password]  = @Password";
using(var command = new SqlCommand(sql, con))
{
    con.Open();
    command.Parameters.AddWithValue("@UserName", txtUserName.Text);
    command.Parameters.AddWithValue("@Password", txtPassword.Text);
    // ...
}

Upvotes: 4

Andrew Diamond
Andrew Diamond

Reputation: 6335

Instead of

String str1 = String.Format("SELECT * FROM [employeeAccount] WHERE [User Name] LIKE '{0}'", txtUserName.Text);
String str2 = String.Format("SELECT * FROM [employeeAccount] WHERE [Password] LIKE '{0}'", txtPassword.Text);

Do

String str1 = String.Format("SELECT * FROM [employeeAccount] WHERE [User Name] LIKE '{0}', SELECT * FROM [employeeAccount] WHERE [Password] LIKE '{1}", txtUserName.Text, txtPassword.Text);

Upvotes: 0

Related Questions