问题描述
这是我的带条件子句的选择查询,每次我将其称为数据表为空且列表计数为0时,请更正我的选择查询或ado.net代码。我想从这些参数从sql Server获取数据,但我不知道我的SQL查询错误还是ado.net代码错误
public List<AdsModel> GetAds(string _location,Int64 _maxprice,Int64 _minprice,int _maxarea,int _minarea)
{
connection();
List<AdsModel> AdsModelList = new List<AdsModel>();
sqlCommand cmd = new sqlCommand("select * from propertydata_tbl where Location like '%@location%' and Price >= @minprice and Price <= @maxprice and Area >= @minarea and Area <= @maxarea",con);
cmd.Parameters.AddWithValue("@location",_location);
cmd.Parameters.AddWithValue("@minprice",_minprice);
cmd.Parameters.AddWithValue("@maxprice",_maxprice);
cmd.Parameters.AddWithValue("@minarea",_minarea);
cmd.Parameters.AddWithValue("@maxarea",_maxarea);
sqlDataAdapter da = new sqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.open();
da.Fill(dt);
con.Close();
if (dt != null)
{
foreach (DaTarow dr in dt.Rows)
{
AdsModelList.Add(
new AdsModel
{
id = Convert.ToInt32(dr["Id"]),price = Convert.ToInt64(dr["Price"]),location = Convert.ToString(dr["Location"]),area = Convert.ToInt32(dr["Area"]),postdate = Convert.ToString(dr["Postdate"]),titlelink = Convert.ToString(dr["Titleline"]),adlink = Convert.ToString(dr["Adlink"])
}
);
}
}
return AdsModelList;
}
解决方法
ADO不会插入字符串,而是将单引号内的所有内容都视为发送给SQL的字符串文字。您应该从以下文字中提取@location
:
SqlCommand cmd = new SqlCommand("select * from propertydata_tbl where Location like '%' + @location + '%' and Price >= @minprice and Price <= @maxprice and Area >= @minarea and Area <= @maxarea",con);
// Here --------------------------------------------------------------------------------^-----------^