【问题标题】:Why is the 2nd Command inside a Connection does not work?为什么连接内的第二个命令不起作用?
【发布时间】:2016-05-06 20:31:51
【问题描述】:

我正在尝试根据用户在登录 TextBox 中输入的内容在两个表中进行测试,因此我测试 LoginName 是否在表“Redacteur”中;否则我会创建一个新的命令来查看另一个表“Membres”。 问题是:当我输入表“Redacteur”中的登录名时,该命令有效,但是一旦我输入属于成员表的登录名,它不会将我重定向到我在代码中请求的页面。我认为它甚至没有进入 Else 部分。

using(SqlConnection connect = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("select * from Redacteurs where RedCode= @lg", connect);
    cmd.Parameters.AddWithValue("@lg", TextLogIn.Text);
    connect.Open();
    //cmd.ExecuteNonQuery();
    SqlDataReader rd = cmd.ExecuteReader();
    if (rd.HasRows)
    {
        rd.Read();
        Session["code"] = rd["RedCode"].ToString();
        Session["loginname"] = TextLogIn.Text;
        Session["pass"] = TextPass.Value;
        Response.Redirect("RedacteurPage.aspx?Redact=" 
            + Session["loginname"].ToString());
        rd.Close();
    }
    else
    {
        cmd = new SqlCommand("select * from Membres where LoginMembre = @lm", connect);
        cmd.Parameters.AddWithValue("@lm", TextLogIn.Text);
        //cmd.ExecuteNonQuery();
        SqlDataReader rd2 = cmd.ExecuteReader();
        if (rd2.HasRows)
        {
            rd2.Read();
            Session["code"] = rd2["MembreCode"].ToString();
            Session["loginname"] = TextLogIn.Text;
            Session["pass"] = TextPass.Value;
            Response.Redirect("ProductCatalogue.aspx?user=" + rd2["FullName"]);
            rd2.Close();
        }
    }
}

【问题讨论】:

  • 你在这里为 SQL 注入打开了大门。
  • I think it doesn't even enter the Else section 您应该使用调试器验证这一点
  • 试试把cmd = new SqlCommand(...)换成cmd.CommandText = "NEW SQL"
  • @Kramb 我正在使用参数来防止注射。

标签: c# asp.net asp.net-mvc asp.net-mvc-4 webforms


【解决方案1】:

您需要先关闭/处置第一个命令,然后才能在同一连接上执行一个命令。

快速而简单(即可行但不推荐)的解决方案是将rd.Close() 放在else 块的第一行。

【讨论】:

  • @Kramb 这是一个参数化查询——注入漏洞到底在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多