【问题标题】:Selecting two columns for SqlCommand class为 SqlCommand 类选择两列
【发布时间】:2015-04-06 19:10:09
【问题描述】:

我想知道是否有一种方法可以为单个 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);

【问题讨论】:

  • 您对sql injection attacks 敞开心扉。请使用任何语言的绑定参数。 C# 有它们,使用它们。

标签: c# sql sql-server


【解决方案1】:

只需在您的 sql 查询和 sql-parameters 中使用 AND 来防止 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);
    // ...
}

【讨论】:

  • 好答案,但不应该是OR吗?以及为什么将% 作为参数值传递?
  • @stakx:我不确定,也许吧。目前还不清楚 OP 实际想要实现的目标。根据%:这只是我回答的一部分。我的第一个版本包含LIKE,但它是多余的。
【解决方案2】:

需要改进的地方很少....

  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*?

【讨论】:

  • @fubo,我在同一时间回复了,我不认为我可以在一分半钟内复制那么多。顺便说一句,您是否错过了所有其他细节?
【解决方案3】:

代替

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

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

【讨论】:

    猜你喜欢
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2014-09-04
    相关资源
    最近更新 更多