程序人生系列之新闻发布系统 1217

1.重构 SQLHelper

SQLHelper中主要有几个方法:执行(带参数数组的)SQL增删改语句和执行(带参数数组的)SQL查询语句  【参数数组可能有可能无】

但是执行的语句可能是 SQL语句 也有可能是 存储过程

所以重构一下SQLHelper,在方法的参数中加入 CommandType,在方法体中指定 CommandType是 Text 还是 StoredProcedure

  public DataTable ExecuteQuery(string sql, SqlParameter[] paras, CommandType ct)

  {

  DataTable dt = new DataTable();

  cmd = new SqlCommand(sql, GetConn());

  cmd.CommandType = ct;

  cmd.Parameters.AddRange(paras);

  using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))

  {

  dt.Load(sdr);

  }

  return dt;

  }

  2.存储过程

  类似函数,将一系列的代码写到一起,可以显示调用

  例如:根据类别编号取出该类别的所有新闻

  编写存储过程:

ALTER PROCEDURE [dbo].[news_selectByCaId]

@caId int

AS

BEGIN

     select n.id, n.title, n.createTime,c.name as caName,n.caId from news n

     inner join category c on n.caId=@caId and n.caId=c.id

     order by n.createTime desc

END 

  调用存储过程的代码:

   public DataTable SelectByCaId(string caId)

  {

  DataTable dt = new DataTable();

  string cmdText = "news_selectByCaId";

  SqlParameter[] paras = new SqlParameter[]{

  new SqlParameter("@caId",caId)

  };

  dt = sqlhelper.ExecuteQuery(cmdText, paras, CommandType.StoredProcedure);

  return dt;

  }

又例如:更新新闻 的存储过程,变量声明时用逗号隔开,另外注意 content 是 text

ALTER PROCEDURE [dbo].[news_update]

@id int,

@title varchar(1000),

@content text,

@caId int

AS

BEGIN

     update news

     set title=@title,content=@content,caId=@caId

     where id=@id   

END

又例如:选择热点新闻,注意 group by 语句

ALTER PROCEDURE dbo.news_selectHotNews

AS

BEGIN

  select top 5 n.id, n.title, n.createTime,c.id as caId,c.[name] as caName,COUNT(rem.id) as comCount

  from news n

  left join category c on c.id=n.cid

  left join remark rem on rem.nid=n.id

  group by n.id, n.title, n.createTime,c.[name],c.id

  order by comCount desc

END

3. 第17集 讲到了 如果使用 自定义 模板!!!

4.  BLL层: 业务逻辑层

编写BLL层: 简单地说就是 把DAL层封装一下!

  public class CategoryManager

  {

  CategoryDAO cdao = null;

  public CategoryManager()

  {

  cdao = new CategoryDAO();

  }

#region

  public DataTable SelectAll()

  {

  return cdao.SelectAll();

  }

#endregion

...

...

}

原文地址:https://www.cnblogs.com/yinger/p/2084848.html