【问题标题】:Combining 'AND , 'OR' in Select statement在 Select 语句中组合 'AND , 'OR'
【发布时间】:2013-06-20 16:21:56
【问题描述】:

Studentname:当用户输入Id或name并点击按钮时,应该显示详细信息......如何?

这里我的 OR 子句在 select 语句中不起作用:

public partial class StudentView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);

    protected void Button1_Click(object sender, EventArgs e)
    {

        string str = "SELECT Registration.UsrFLname, Registration.UsrAddress, Students.STUID, Materials.BookID, Materials.BookName, Courses.CourseName, Courses.CourseFee FROM Courses INNER JOIN Materials ON Courses.BookID = Materials.BookID INNER JOIN Students ON Courses.STUID = Students.STUID AND Materials.STUID = Students.STUID INNER JOIN Registration ON Students.STUID = Registration.STUID AND Registration.UsrFLname = '" + TextBox1.Text + "' OR Students.STUID = '" + TextBox1.Text + "'";

        con.Open();
        SqlCommand cmd = new SqlCommand(str, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds, str);
        GDStudents.DataSource = ds;
        GDStudents.DataBind();
    }
}

谁能帮忙解决这个问题!!

提前致谢!!

【问题讨论】:

  • 定义“不工作”。此外,此代码中存在 SQL 注入安全漏洞。
  • 看在上帝的份上,使用参数化查询!
  • 另外,您找到键盘上的 Enter/Return 键了吗?你听说过 SQL 注入吗?
  • 等一下……让我停止吃午餐来为你做你的工作。我喜欢回答问题,但实际上,这看起来你在放弃并在这里发帖之前没有给它旧的“大学”尝试。
  • 加上 where 子句可能会更好读。

标签: asp.net sql-server


【解决方案1】:

AND 的优先级高于OR

在布尔逻辑中,AND 类似于乘法,OR 类似于求和,因此,当您希望求和在乘法之前发生时,您应该使用括号 ()

2*3+1 = 7
2*(3+1) = 8

我猜你的情况应该是

Students.STUID = Registration.STUID 
   AND 
( -- note this paren
    Registration.UsrFLname = '" + TextBox1.Text + "' 
        OR
    Students.STUID = '" + TextBox1.Text + "'"
) -- note this paren

正如许多人所说,您应该参数化您的查询,并且不要插入最终用户提供的文本。

【讨论】:

    【解决方案2】:

    要回答您的问题,您没有得到预期的结果,因为您没有正确分组布尔运算,当您的意思是 X AND (Y OR Z) 时,您有 X AND Y OR Z。在前者的情况下,只需 Z 或 X 和 Y 的组合为真,整个表达式的计算结果为真。

    另一方面,您在此处的代码对SQL injection 攻击(即real bad完全开放。你应该把它改成parameterized query posthaste。

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多