Reputation: 27
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
Reputation: 223322
Few things to improve....
SqlParameter
LIKE
to compare against user name and password, you probably want exact match 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
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
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