DAL层中根据ID查询GridView行信息方法(常用)

1.首先呢我们要根据ID来进行一个查询

var sql = "select * from Product where id=" + id;

2.我们把查询到的放在一个DataTable对象内。(且大于查询结果大于1,小于1的话返回空)

DataTable dt = SqlHelper.Cx(sql);
            if (dt.Rows.Count<1)
            {
                return null;
            }

3.把查询到的行放入DataRow对象。然后返回这个信息

DataRow row = dt.Rows[0];
            return new Product()
            {
                ProductName = row["ProductName"].ToString(),
                MarketPrice = Convert.ToDouble(row["MarketPrice"]),
                SellingPrice = Convert.ToDouble(row["SellingPrice"]),
                CategoryId = Convert.ToInt32(row["CategoryId"]),
                Introduction = Convert.ToString(row["Introduction"]),
                IsOnSale = Convert.ToInt32(row["IsOnSale"]),
                Addtime = Convert.ToString(row["Addtime"]),
            };

我们看下整体代码:

 public static Product Select(int id)
        {
            var sql = "select * from Product where id=" + id;
            DataTable dt = SqlHelper.Cx(sql);
            if (dt.Rows.Count<1)
            {
                return null;
            }

            DataRow row = dt.Rows[0];
            return new Product()
            {
                ProductName = row["ProductName"].ToString(),
                MarketPrice = Convert.ToDouble(row["MarketPrice"]),
                SellingPrice = Convert.ToDouble(row["SellingPrice"]),
                CategoryId = Convert.ToInt32(row["CategoryId"]),
                Introduction = Convert.ToString(row["Introduction"]),
                IsOnSale = Convert.ToInt32(row["IsOnSale"]),
                Addtime = Convert.ToString(row["Addtime"]),
            };
        }

这就是我们根据ID来查询行信息的方法~

 

你可能感兴趣的:(DAL层中根据ID查询GridView行信息方法(常用))