山寨一个PetShop(Task002)——数据类库Model

源代码:13033480群共享

首先要提到的是,PetShop代码,通篇都没有使用DataAdapter类,当然也没有使用和它配套的数据集DataSet

ADO.NET Framework支持两种数据访问模式,一种是使用SqlConnectionSqlCommandSqlDataReader来访问数据库;一种是使用DataAdapterDataSet访问数据库。按照《ASP.NET 2.0揭秘》一书的观点,后一种访问模式,会使性能降低,同时会占用大量的硬件资源,“使用DataReader类获取500条记录,比使用DataReader类获取同样的500条记录要快得多。”

使用DataAdapterDataSet访问数据库,主要特点是,可以把读取和要写入的数据先存放在内存中的数据集DataSet中,然后使用DataAdapterFill()Update()函数,一次性读取或写入到数据库中。PetShop访问数据库,也是采用了这种逻辑,只是用Model中的类,取代了DataSet

Model中的类,是根据数据库量身定做的数据库,或者说是数据类型。CategoryInfo.csProductInfo.cs都直接是数据库的映射,都可以直接存放相应数据库中的一行数据。而ItemInfo.cs刚灵活地映射了表CateogryProductItemInvention三个表内联形成的商品的商品信息。

特别提到的是,Model中的类,只可以存放一行数据信息,如果要存放表格数据信息,则要使用列表List,以Category为例,IList<CategoryInfo> categories = new List<CategoryInfo>();定义了一个CategoryInfo的列表,然后,使用DataReader,把读取的数据库信息,一行一行地写入存放在内存中的列表中。

【操作步骤】

一、右击Web→添加新项Web配置文件

二、添加连接字符串

  <connectionStrings>
    <add name="SQLConnString1" connectionString="server=.\SQLEXPRESS;database=NetShop;integrated security=SSPI;min pool size=4;max pool size=4;" providerName="System.Data.SqlClient"/>
  </connectionStrings>


 

三、复制Model中的CategoryInfo.c

四、Default.aspx中添加控件ListBox

        <div>
            <asp:ListBox ID="lstCategories" runat="server">
            </asp:ListBox>
        </div>

五、Default.aspx.cx中添加如下代码

public partial class _Default : System.Web.UI.Page 
{
    private const string SQL_SELECT_CATEGORIES = "SELECT CategoryId, Name, Descn FROM Category";

    protected void Page_Load(object sender, EventArgs e)
    {

        IList<CategoryInfo> categories = new List<CategoryInfo>();

        //数据库基本操作
        String connectionString = ConfigurationManager.ConnectionStrings["SQLConnString1"].ConnectionString;

        SqlCommand cmd = new SqlCommand();
        SqlConnection conn = new SqlConnection(connectionString);
        conn.Open();

        cmd.Connection = conn;
        cmd.CommandText = SQL_SELECT_CATEGORIES;
        cmd.CommandType = CommandType.Text;

        SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        //数据保存到Model中
        while (rdr.Read())
        {
            CategoryInfo cat = new CategoryInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetString(2));
            categories.Add(cat);
        }

        conn.Close();

        //数据绑定绑定到用户界面
        lstCategories.DataSource = categories;
        lstCategories.DataTextField = "Name";
        lstCategories.DataValueField = "ID";//Model中的字段与数据库表中的字段一样,是不是更好?
        lstCategories.DataBind();
    }
}


 

六、代码中使用了ListConfigurationManagerModel中的类,需要添加相应的引用,并导入相应的命名空间。

using System.Collections.Generic;

using System.Configuration;

using NetShop.Model;

七、浏览并查看结果

【技术要点】

1、  连接字符串

2、  数据库模型Model

3、IList、List

原文地址:https://www.cnblogs.com/java20130723/p/3211656.html