【问题标题】:select query with where clause in ado.net using asp.net mv使用asp.net mv在ado.net中选择带有where子句的查询
【发布时间】:2020-12-20 00:33:00
【问题描述】:

这是我每次调用时带有 where 子句的选择查询数据表为空且列表计数为 0 请更正我的选择查询或 ado.net 代码。我想通过这些参数从 SQL 服务器获取数据,但我不知道我的 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;
        }

【问题讨论】:

标签: c# sql asp.net ado.net sqldatareader


【解决方案1】:

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 --------------------------------------------------------------------------------^-----------^

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多