【发布时间】:2021-04-01 21:39:15
【问题描述】:
我有这行代码
string sqlQuery = "SELECT studentid,StudentName,age,contact FROM tblStudent2 ";
if (txtStudentName.Text != "" && txtStudentId.Text != "" && txtAge.Text != "" && txtContact.Text != "")
{
sqlQuery += " Where ";
if (txtStudentName.Text != "")
{
sqlQuery += "studentId = '" + txtStudentName.Text + "'";
}
sqlQuery += " and ";
if (txtStudentId.Text != "")
{
sqlQuery += "studentId = '" + txtStudentId.Text + "'";
}
sqlQuery += " and ";
if (txtAge.Text != "")
{
sqlQuery += "age ='" + txtAge.Text + "'";
}
sqlQuery += " and ";
if (txtContact.Text != "")
{
sqlQuery += " FROM tblStudent2 Where contact ='" + txtContact.Text + "'";
}
}
我的问题目标是从表中选择 (tblStudent2) 。有了这个 SQL 语句
"SELECT studentid,StudentName,age,contact FROM tblStudent2 " + "and (TableColumns) and (TableColumns)""
但目标是在嵌套的 IF 参数之间添加“and”,如果我将其添加到 if 语句中,如果我追加,结果 sqlQuery 将导致“and”作为句子的最后一个单词“和”字。
【问题讨论】:
-
连接 SQL 是灾难的根源。不要这样做。使用参数化查询,以免成为Little Bobby Tables 的受害者。 Stack Overfow 和 Oracle 的网站上有大量关于它的信息。
-
我有一个单独的函数来解析这个查询。我的单独函数已经过测试,我猜它对 sql 注入具有弹性。我了解sql注入的危险。谢谢你警告我。