如何在SELECT SqlCommand中替换SqlParamter?

时间:2016-05-13 09:24:54

标签: c# ado.net

在现有的代码库中有硬编码的SQL,我想避免SQL注入。

以下代码将SqlCommand与SqlParameters一起使用。查询不返回任何数据。但是,当我删除参数时,查询返回正确的结果。

如何将SqlParameters与SELECT语句一起使用?

        string atUsername = "@username"; //does not work
        //string atUsername = "Demo1"; //THIS WORKS
        string atPassword = "@password"; //does not work
        //string atPassword = "222"; //THIS WORKS
        string sql = @"SELECT userId, userName, password, status, roleId, vendorId 
        FROM users 
        WHERE username = '" + atUsername + "' AND password = '" + atPassword + "'";

        SqlCommand cmd = new SqlCommand(sql);

        cmd.Parameters.Add(atUsername, SqlDbType.NVarChar, 20);
        cmd.Parameters[atUsername].Value = "Demo1";
        //cmd.Parameters.AddWithValue //also does not work


        cmd.Parameters.Add(atPassword, SqlDbType.NVarChar, 20);
        cmd.Parameters[atPassword].Value = "222";
        //cmd.Parameters.AddWithValue //also does not work

        SqlConnection conn = new SqlConnection(connStr);
        cmd.Connection = conn;
        conn.Open();

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        Console.WriteLine(dt.Rows != null);
        if (dt.Rows != null)
        {
            Console.WriteLine(dt.Rows.Count);
        }

        conn.Close();
        conn.Dispose();

我使用

尝试了替代方案也没有成功
  1. SqlCommand.ExecuteReader和SqlDataReader
  2. IDisposable pattern
  3. cmd.Parameters.Add(atUsername替换为

    SqlParameter pUsername = new SqlParameter(); pUsername.ParameterName = atUsername; pUsername.Value = "Demo1"; cmd.Parameters.Add(pUsername);"

  4. PS。我听说过EntityFramework,但在这种情况下我不能使用EF(长篇故事)。

1 个答案:

答案 0 :(得分:3)

问题的根源是你在字符串文字中使用变量名:

 WHERE username = '@username' AND password = '@password'

因此sql server不会将它们视为变量名。而是搜索名称为“@username”且密码为“@password”的用户。正确的方法是:

WHERE username = @username AND password = @password