关键字'和'附近的语法不正确。字符串''后面的未闭合引号

时间:2015-12-07 05:33:51

标签: c# asp.net

 query = "select StudentName,FatherName,ContactNo from Student  where Class='" 
           + cmbClass.Text == null ? "" : cmbClass.Text.Trim() + " and isActive=1 '";    
 }
 else if (!cmbSection.Text.Contains("Select"))
 {
   query += " and Section='" + cmbSection.Text == null ? "" 
                                                       : cmbSection.Text.Trim() + "' ";
 }

1 个答案:

答案 0 :(得分:1)

您为Class ='打开了单引号,但在关闭另一个单引号之前将isActive = 1。从isActive = 1的右侧移动到它前面,如下所示。

低于C#6版本:

if(/*your clause*/) 
{
  query = string.Format("SELECT StudentName, FatherName, ContactNo FROM Student WHERE Class='{0}' AND isActive = 1", cmbClass.Text == null ? string.Empty : cmbClass.Text.Trim()) //<-- you quote was meant for Class but was on wrong side of isActive
} 

if (!cmbSection.Text.Contains("SELECT")) //<--- else probably shouldn't be there or you will never hit this clause after going in the above if
{
  query += string.Format(" AND Section='{0}' ", cmbSection.Text == null ? string.Empty : cmbSection.Text.Trim())
}

C#6版本:

if (/*your clause*/)
{
    var classText = cmbClass.Text == null ? string.Empty : cmbClass.Text.Trim()
    query = $"SELECT StudentName, FatherName, ContactNo FROM Student WHERE Class='{classText}' AND isActive = 1", ) //<-- you quote was meant for Class but was on wrong side of isActive
} 

if (!cmbSection.Text.Contains("SELECT"))
{
   var section = cmbSection.Text == null ? string.Empty : cmbSection.Text.Trim();
   query += $" AND Section='{section}'";
}

此外,您不应该以这种方式构建查询,这是不好的做法。您应该熟悉SqlCommand并且它与SqlClient相关。