2015-02-06 53 views
0

我想知道是否有一種方法可以在同一個表中爲單個SqlCommand選擇兩列,之後將這兩列用於比較兩列中的數據和兩個文本框中的數據:爲SqlCommand類選擇兩列

下面是兩個字符串是我此刻的SqlCommand類使用,並想將它們放在一起:

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); 
+3

你是寬打開[sql注入攻擊](http://en.wikipedia.org/wiki/SQL_injection)。請使用您可以使用的任何語言的綁定參數。 C#擁有它們,使用它們。 – nvoigt 2015-02-06 15:37:00

回答

4

只需使用AND在您的SQL查詢和SQL參數以防止SQL注入:

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); 
    // ... 
} 
+0

很好的答案,但不應該是'OR'嗎?爲什麼你將'%'作爲參數的值? – stakx 2015-02-06 15:39:06

+0

@stakx:我不確定,也許。這並不清楚OP究竟在努力實現什麼。根據'%':這只是我答案的一部分。我的第一個版本包含'LIKE',但它是多餘的。 – 2015-02-06 15:39:43

0

而不是

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); 

不要

​​
1

幾件事情,以改善....

  1. 不要使用字符串連接/格式化以形成SQL查詢,您很容易進行SQL注入。 參數化您的查詢。使用SqlParameter
  2. 重要!。不要使用LIKE進行比較的用戶名和密碼,您使用=
  3. 你需要使用AND運營商兩個條件結合起來可能要精確匹配。

所以,你的代碼應該是這樣的:

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 
} 

最後一件事補充,不存儲在數據庫中密碼的文本,而不是存儲它們的哈希值,請參閱:How to store passwords *correctly*?

+0

@fubo,我在同一時間後回覆說,我認爲我不會在一分半鐘內複製那麼多。順便說一下,你錯過了所有其他的細節? – Habib 2015-02-06 15:52:50