我在这一行上收到错误:
using (SqlDataReader reader =cmd.ExecuteReader())
我正在研究ASP.Net中的AJAX级联下拉示例,下面是我的代码。由于错误
,我无法运行代码'='附近的语法不正确。附近使用(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;
}
}
}
答案 0 :(得分:0)
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 CITY,其中StateId = CA”,这是无效的。需要引用作为字符串传递的值。但是不要只在“{0}”周围加上引号 - 正确的解决方法是使用参数化查询并将StateId作为参数传递。类似的东西:
string sql = "select [CityName], [CityId] FROM Cities where StateId = @stateId"
cmd.Parameters.Add("stateId", stateId);
效率更高,可以保护您免受SQL injection。
的攻击