2015-11-12 48 views
-3

我正在创建一个asp web表单页面,此部分正在构建查询,并且在添加boatYear部件时引发异常。在数据库中它是一个smallintSQL异常关键字'And'附近的语法错误

类型“System.Data.SqlClient.SqlException”的异常出现在System.Data.dll中,但在用户代码中没有处理

附加信息:关键字“与”附近有语法错误。

查询:

string qs = Request.QueryString["dir"].ToString(); 
    string sql = "Select * From Boats "; 
    string boatClass = ""; 
    string boatYear = ""; 
    string boatMake = ""; 
    string boatUsedNew = ""; 

    if (qs.Equals("f")) 
    { 
     boatClass = (string)Session["class"]; 
     boatYear = (string)Session["year"]; 
     boatMake = (string)Session["make"]; ; 
     boatUsedNew = (string)Session["usednew"]; 
    } 

    string where = ""; 

    if (qs != "b") 
    { 
     if (boatClass != "all" && boatClass != "") 
     { 
      where = "Where Class = '" + boatClass + "'"; 
     } 

     if (boatYear != "all" && boatYear != "") 
     { 
      if (where == "") 
      { 
       where += "Where "; 
      } 
      else 
      { 
       where += " AND "; 
      } 
      where += "Year = " + boatYear; 
     } 

     if (boatMake != "all" && boatMake != "") 
     { 
      if (where == "") 
      { 
       where += "Where "; 
      } 
      else 
      { 
       where += " AND "; 
      } 
      where += "Make = '" + boatMake + "'"; 
     } 

     if (boatUsedNew != "all" && boatUsedNew != "") 
     { 
      if (where == "") 
      { 
       where += "Where "; 
      } 
      else 
      { 
       where += " AND "; 
      } 
      where += "UsedOrNew = '" + boatUsedNew + "'"; 
     } 

     sql += where; 
     Session["sql"] = sql; 
    } 
    else 
    { 
     sql = (string)Session["sql"]; 
    } 
+5

您是否尝试打印出您的SQL? –

+3

这是非常糟糕的做法,它容易出现很多错误。它很难阅读......你应该简单地调试生成的sql。你的条件很奇怪。你知道你可以使用string.IsNullOrEmpty()正确吗? – JonH

+7

呃。为什么不'WHERE 1 = 1',那么你可以简单地使用'AND'来添加新的子句。这会大大地降低你的代码... –

回答

2

正如指出的那样,这种做法很容易受到SQL注入 - https://en.wikipedia.org/wiki/SQL_injection。为了保护你的代码免受SQL注入攻击,你应该使用参数化查询,在这些条件下你可以放置参数名称而不是直接值。编写SQL语句仍然可以使用字符串列表完成。

List<string> conditions = new List<string>(); 

if (boatClass != "all" && !string.IsNullOrEmpty(boatClass)) 
    conditions.Add("[Class] = @boatClass"); 
if (boatYear != "all" && !string.IsNullOrEmpty(boatYear)) 
    conditions.Add("[Year] = @boatYear"); 
if (boatMake != "all" && !string.IsNullOrEmpty(boatMake)) 
    conditions.Add("[Make] = @boatMake"); 
if (boatUsedNew != "all" && !string.IsNullOrEmpty(boatUsedNew)) 
    conditions.Add("[UsedOrNew] = @boatUsedNew"); 

if (conditions.Count > 0) 
    sql += " where " + string.Join(" AND ", conditions); 

然后,当然,正确类型的参数应该传递给设置并使用此SQL运行命令的代码。

+0

我仍然得到相同的异常 – cbass0

+6

快乐SQL注入聚会 – Steve

+0

@Steve - mea culpa! – Igor

相关问题