SQL异常关键字'And'附近的语法不正确

时间:2015-11-12 18:54:39

标签: c# sql asp.net sql-server

我正在创建一个asp web表单页面,这部分正在构建一个查询,并且在添加boatYear部分时会抛出异常。在数据库中,它是smallint

  

System.Data.dll中出现'System.Data.SqlClient.SqlException'类型的异常,但未在用户代码中处理

     

其他信息:关键字“AND”附近的语法不正确。

查询:

    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"];
    }

1 个答案:

答案 0 :(得分: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设置和运行命令的代码。