首页 > 解决方案 > 如何在asp.net mvc 3.1 c#中按Id获取列行

问题描述

我有一个名为“产品”的数据库表。该表包含具有几个字段的产品,例如“ProductId”、“ProductName”和“ProductPrice”。我想创建一个函数,通过它的 ProductId 获取表中行的值,以便我可以将这些值存储在 cookie 中。如何仅使用 ProductId 作为参数获取一行表“产品”?(没有实体框架)。

标签: c#asp.netasp.net-coremodel-view-controller

解决方案


using (SqlConnection con = new SqlConnection("data source=xxxx;user id=sa;password=xxxxx;integrated security=yes"))
            {
                SqlDataAdapter da = new SqlDataAdapter("select * from Products where ProductId=" + ProductId);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Console.WriteLine(string.Format("ProductName - {0} and ProductPrice -{1}", ds.Tables[0].Rows[0]["ProductName"].ToString(),
                        ds.Tables[0].Rows[0]["ProductPrice"].ToString()));
                }
            }

推荐阅读