WebMethod在'='"附近抛出“语法错误”

本文关键字:语法 错误 语法错误 quot WebMethod | 更新日期: 2023-09-27 17:49:24

我在这一行得到错误:using (SqlDataReader reader =cmd.ExecuteReader())

我在ASP的AJAX级联下拉示例工作。下面是我的代码。由于错误

,我无法运行代码。

'='附近语法错误。near using (SqlDataReader reader =cmd.ExecuteReader())

代码
 [WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownCountry1(string knownCategoryValues)
{
   // select CountryId, Country from Country where Status='Active'
   // string query = "SELECT Country, CountryId FROM Country";
    string query = "select [CountryName], [CountryId] from Countries";
    List<AjaxControlToolkit.CascadingDropDownNameValue> countries = GetData(query);
    return countries.ToArray();
}
private List<AjaxControlToolkit.CascadingDropDownNameValue> GetData(string query)
{
    string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    List<AjaxControlToolkit.CascadingDropDownNameValue> values = new List<AjaxControlToolkit.CascadingDropDownNameValue>();
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        cmd.Connection = con;
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
            {
                values.Add(new AjaxControlToolkit.CascadingDropDownNameValue
                {
                    name = reader[0].ToString(),
                    value = reader[1].ToString()
                });
            }
            reader.Close();
            con.Close();
            return values;
        }
    }
}

WebMethod在'='"附近抛出“语法错误”

string state = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["StateId"];
string query = string.Format("select [CityName], [CityId] FROM Cities where StateId = {0}", state);

如果state是像"CA"这样的字符串,那么这将生成SQL语句"select [CityName], [CityId] FROM Cities where StateId = CA",这是无效的。作为字符串传递的值需要加引号。但是不要只是在"{0}"周围加上引号—正确的解决方法是使用参数化查询并将StateId作为参数传递。比如:

string sql = "select [CityName], [CityId] FROM Cities where StateId = @stateId"
cmd.Parameters.Add("stateId", stateId);